[R] for() loop question

Marc Schwartz MSchwartz at mn.rr.com
Sat Aug 26 19:16:20 CEST 2006


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



More information about the R-help mailing list