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

后端 未结 2 1779
小蘑菇
小蘑菇 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
    

提交回复
热议问题