[R] For loops

MacQueen, Don macqueen1 at llnl.gov
Wed Apr 11 17:19:42 CEST 2012


In addition to what Jeff and David have said...

If you really want to create a separate data frame for each subgroup then
you need use the assign function, and also data.split[[i]] instead of
data.split[1].

for (i in 1:3) {
   assign( paste('sub',i,sep='') , data.split[[i]]
}

Jeff showed you how to skip the splitting, by subsetting within the loop.

'class' is also a R built-in function name, and thus not a good choice for
one's on use.

-Don

-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 4/9/12 2:33 PM, "Christopher Desjardins" <cddesjardins at gmail.com> wrote:

>Hi,
>I am having trouble with syntax for a for loop. Here is what I am trying
>to
>do.
>
>class=c(rep(1,3),rep(2,3),rep(3,3))
>out1=rnorm(length(class))
>out2=rnorm(length(class))
>out3=rnorm(length(class))
>data=data.frame(class,out1,out2,out3)
>
>dat.split=split(data,data$class)
>  for(i in 1:3){
>  sub[i]=dat.split[i]
>  }
>
>However, the for loop doesn't work. I want to assign each split to a
>different data object. Better yet, how I could assign each class to a
>separate object and skip the splitting?
>
>Thanks,
>Chris
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org 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.



More information about the R-help mailing list