[R] For loops

David Winsemius dwinsemius at comcast.net
Tue Apr 10 00:21:09 CEST 2012


On Apr 9, 2012, at 5:33 PM, Christopher Desjardins 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.

Why? What's wrong with leaving them in a list that split() provides.

In that form you can easily use lapply() and start your 12 step  
program away from for-loop addiction.

> Better yet, how I could assign each class to a
> separate object and skip the splitting?
>
--

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list