Subsetting a data frame for all the unique values of a row

3.8k views Asked by At

Suppose I have a data frame as:

id   value
1    "hi"
1    "hi"
1    "hi again"
1    "hi again"
2    "hello"
2    "hi"

Now I want to get a separate data frame for each of the distinct values in id column.

df1
    id    value
    1     "hi"
    1     "hi"
    1     "hi again"
    1     "hi again"
and df2 
    id    value
    2     "hello"
    2     "hi"

How to achieve this efficiently in R ?

I tried doing the for loop

 df <- data.frame(id=c('1','1','1','1','2','2'),value=c('hi','hi','hi again','hi again','hello','hi'))
 for (i in 1:length(unique(df$id)))  {
         df1 <- df[unique(df$id)[i],]
         print(df1)
     }

But the result is

id value
1  1    hi
  id value
2  1    hi

I understand that apply family does the same for every row in a data frame, but I am not able to use them in this situation. May be I am missing something obvious ?

1

There are 1 answers

0
lotus On BEST ANSWER

In light of the comments above, command to assign data frames individually added.

df_list <- split(df, df$id)
names(df_list) <- c("df1", "df2")
list2env(df_list, envir = .GlobalEnv)