I have a data.frame in R. I want to create three different data.frame using a loop and subset function. I have a large data.frame, but what I need is in the example below:
sex<-c("M","M","M","F","M","F")
age<-c(20,18,17,20,18,17)
name<-c("John", "Joseph", "Bill", "Sarah", "Robert", "Dana")
data<-data.frame(sex, age, name)
>data
sex age name
1 M 20 John
2 M 18 Joseph
3 M 17 Bill
4 F 20 Sarah
5 M 18 Robert
6 F 17 Dana
What I want is:
>age17
sex age name
1 M 17 Bill
2 F 17 Dana
>age18
sex age name
1 M 18 Joseph
2 M 18 Robert
>age20
sex age name
1 M 20 John
2 F 20 Sarah
I can use the commands below:
>age17<-subset(data, data[,2]==17)
>age18<-subset(data, data[,2]==18)
>age20<-subset(data, data[,2]==20)
But it is possible to use a loop to reduce the size of commands?
split.