[R] new data frame for loop

2007-06-07 Thread Emily Broccoli
I have a data frame with three columns, one coded as a factor. I would like
to separate my data out into separate data frames according to the factor
level. Below is a simple example to illustrate. I can get R to return the
data in the correct format but cannot work out how to get separate data
frames. I am a newcommer to programming in R so am not sure what I am
missing! Thanks, Emily

a-seq(1,20, by=2)
b-seq(1,30, by=3)
ID-as.factor(c(1,1,1,2,2,2,3,3,3,3))
df-data.frame(a,b,ID)
for(i in 1:length(unique(ID))) {
df2-subset(df, select=a:b, ID==ID[i])
}

[[alternative HTML version deleted]]

__
R-help@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.


Re: [R] new data frame for loop

2007-06-07 Thread Tobias Verbeke
Hi Emily,

Emily Broccoli wrote:

 I have a data frame with three columns, one coded as a factor. I would like
 to separate my data out into separate data frames according to the factor
 level. Below is a simple example to illustrate. I can get R to return the
 data in the correct format but cannot work out how to get separate data
 frames. I am a newcommer to programming in R so am not sure what I am
 missing! Thanks, Emily
 
 a-seq(1,20, by=2)
 b-seq(1,30, by=3)
 ID-as.factor(c(1,1,1,2,2,2,3,3,3,3))
 df-data.frame(a,b,ID)

The function split will give you a list
of data frames split according to a factor:

  split(df, df$ID)
$`1`
   a b ID
1 1 1  1
2 3 4  1
3 5 7  1

$`2`
a  b ID
4  7 10  2
5  9 13  2
6 11 16  2

$`3`
 a  b ID
7  13 19  3
8  15 22  3
9  17 25  3
10 19 28  3

See ?split.

HTH,
Tobias

-- 

Tobias Verbeke - Consultant
Business  Decision Benelux
Rue de la révolution 8
1000 Brussels - BELGIUM

+32 499 36 33 15
[EMAIL PROTECTED]

__
R-help@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.