Home > Software engineering >  Make list by group from columns in R
Make list by group from columns in R

Time:10-16

Suppose we have the data frame as follows:

df <- data.frame(a= rep(c(1:6), 4), b= c(rep('x',6), rep('y', 6), rep('z', 6), rep('f', 6)))

I want to make list contains data frames from the data frame "df" as follows

lst <-list(df1 = data.frame(v1= c(1, 1, 1, 1), v2= (x, y, z, f),
           df2 = data.frame(v1= c(2, 2, 2, 2), v2= (x, y, z, f), 
           df3 = data.frame(v1= c(3, 3, 3, 3), v2= (x, y, z, f),
           df4 = data.frame(v1= c(4, 4, 4, 4), v2= (x, y, z, f),
           df5 = data.frame(v1= c(5, 5, 5, 5), v2= (x, y, z, f),
           df6 = data.frame(v1= c(6, 6, 6, 6), v2= (x, y, z, f))

I have no idea how to achieve that.

Suppose they are not of the same length. I want to skip the missing values of some variables. and group the remainder.

newdf <- data.frame(a= c(1:5,rep(c(1:6), 2),1:4), b= c(rep('x',5), rep('y', 6), rep('z', 4), rep('f', 6)))

I want the new list to be as follows:

newlst <- list(df1 = data.frame(v1= c(1, 1, 1, 1), v2= (x, y, z, f),
               df2 = data.frame(v1= c(2, 2, 2, 2), v2= (x, y, z, f), 
               df3 = data.frame(v1= c(3, 3, 3, 3), v2= (x, y, z, f),
               df4 = data.frame(v1= c(4, 4, 4, 4), v2= (x, y, z, f),
               df5 = data.frame(v1= c(5, 5, 5), v2= (x, y, f),
               df6 = data.frame(v1= c(6, 6), v2= (y, f))

CodePudding user response:

does split(newdf, ~a) work for you?

  • Related