Create multiple data frames from one based off values with a for loop

后端 未结 2 1750
小蘑菇
小蘑菇 2021-01-06 08:23

I have a large data frame that I would like to convert in to smaller subset data frames using a for loop. I want the new data frames to be based on the the values in a colum

相关标签:
2条回答
  • 2021-01-06 09:00

    If you want to create separate objects in a loop, you can use assign. I used unique because you said you had many levels.

     for(i in unique(df$y)) {
            nam <- paste("df", i, sep = ".")
            assign(nam, df[df$y==i,])
            }
    
    > df.A
      x y
    1 1 A
    2 2 A
    3 3 A
    4 4 A
    5 5 A
    6 6 A
    7 7 A
    8 8 A
    > df.B
        x y
    9   9 B
    10 10 B
    11 11 B
    12 12 B
    13 13 B
    14 14 B
    
    0 讨论(0)
  • 2021-01-06 09:01

    I think you just need the split function:

     split(df, df$y)
    $A
      x y
    1 1 A
    2 2 A
    3 3 A
    4 4 A
    5 5 A
    6 6 A
    7 7 A
    8 8 A
    
    $B
        x y
    9   9 B
    10 10 B
    11 11 B
    12 12 B
    13 13 B
    14 14 B
    15 15 B
    16 16 B
    17 17 B
    
    $C
        x y
    18 18 C
    19 19 C
    20 20 C
    

    It is just a matter of properly subsetting the output to split and store the results to objects like dfA <- split(df, df$y)[[1]] and dfB <- split(df, df$y)[[2]] and so on.

    0 讨论(0)
提交回复
热议问题