Dear Lister, If I have a list of number, say x<-c(0.1, 0.5, 0.6...), how to use a for() to loop through each number in x one by one? Thank you so much! wensui [[alternative HTML version deleted]]
On Sat, 2006-08-26 at 13:06 -0400, Wensui Liu wrote:> Dear Lister, > > If I have a list of number, say x<-c(0.1, 0.5, 0.6...), how to use a for() > to loop through each number in x one by one? > > Thank you so much! > > wensuiTwo options: x <- c(0.1, 0.5, 0.6)> for (i in x) {print (i)}[1] 0.1 [1] 0.5 [1] 0.6> for (i in seq(along = x)) {print (x[i])}[1] 0.1 [1] 0.5 [1] 0.6 Which approach you take tends to depends upon what else you are doing within the loop. I would also take a look at ?sapply, depending up what is it you are doing. HTH, Marc Schwartz
let us know what you want to do because the beauty of R is that, in many cases, you may not have to loop. ----- Original Message ----- From: "Wensui Liu" <liuwensui at gmail.com> To: <r-help at stat.math.ethz.ch> Sent: Saturday, August 26, 2006 1:06 PM Subject: [R] for() loop question> Dear Lister, > > If I have a list of number, say x<-c(0.1, 0.5, 0.6...), how to use a for() > to loop through each number in x one by one? > > Thank you so much! > > wensui > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >
Thank you so much Marc. Your solution is exactly what I am looking for. Have a nice weekend. wensui On 8/26/06, Marc Schwartz <MSchwartz at mn.rr.com> wrote:> On Sat, 2006-08-26 at 13:06 -0400, Wensui Liu wrote: > > Dear Lister, > > > > If I have a list of number, say x<-c(0.1, 0.5, 0.6...), how to use a for() > > to loop through each number in x one by one? > > > > Thank you so much! > > > > wensui > > Two options: > > x <- c(0.1, 0.5, 0.6) > > > for (i in x) {print (i)} > [1] 0.1 > [1] 0.5 > [1] 0.6 > > > > for (i in seq(along = x)) {print (x[i])} > [1] 0.1 > [1] 0.5 > [1] 0.6 > > > Which approach you take tends to depends upon what else you are doing > within the loop. > > I would also take a look at ?sapply, depending up what is it you are > doing. > > HTH, > > Marc Schwartz > > >-- WenSui Liu (http://spaces.msn.com/statcompute/blog) Senior Decision Support Analyst Health Policy and Clinical Effectiveness Cincinnati Children Hospital Medical Center