If I have a data.frame like this:
X1 X2
1 1 A
2 2 A
3 3 B
4 4 B
5 5 A
6 6 A
7 7 B
8 8 B
9 9 A
10 10 A
My goal is to define a set of data.frame as:
y1<-data[1:2,]
y2<-data[3:4,]
y3<-data[5:6,] ##...etc. by a loop.
Therefore, ideally I would like to use (for instance) a for loop
for (i in 1:5){
y_i <- data[2*i:2*(i+1), ]
}
However, I cannot figure out how to define a subsequent set of data.frame such as y_i. Is there any method able to do this? Thanks in advance.
You can use assign
. It will help you get the data frames you need with the naming convention you asked for.
for (i in 1:5){
assign(paste("y", i, sep="_"), data[(i*2-1):(i*2), ])
}