Split dataframe by levels of a factor and name dataframes by those levels

后端 未结 3 1288

I want to split an existing dataframe by the levels of one of the factor variables so that the names of the split dataframes would correspond to the levels of the factor.

3条回答
  •  抹茶落季
    2020-11-28 15:22

    sapply( levels( df$Z ), function( x ) list( subset( df, Z == x ) ) )
    

    This will return a list with elements named after the levels of df$Z, each one containing the subset of df.

    Ops, a better answer was provided, but has been deleted -- I will put the solution here:

    split(df, df$Z)
    

提交回复
热议问题