-1

Say I have a large data frame in long format, with each subject occupying 5 rows, with 5 subjects in total.

x=c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5)
df=data.frame(x, 1:25)

Now I want to separate this into 5 separate data frames, one for each subject. I know I could do this:

s01=df[df$x==1,]

5 times, but I want to create all five data frames in one go, using one command. Is there a way to do this (e.g. with a for loop or something like lapply)? I tried with a for loop but not sure how to get it to output 5 separate objects with different names.

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
cmpsych93
  • 65
  • 2
  • 5

1 Answers1

1

You can simply do:

result <- split(df, df$x)

This will return in a list different data frames according to column x. You can take out for example, the first data frame, by

result[[1]]
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248