2

Consider the following data:

myd <- dput(myd)
structure(list(group = c("g1", "g1", "g1", "g1", "g1", "g2", 
"g2", "g2", "g2", "g3", "g3", "g3", "g3", "g3"), X1 = c(0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0), X2 = c(1, 1, 1, 1, 1, 0, 
0, 0, 0, 1, 0, 0, 2, 0), X3 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 
1, 1, 2, 1), X4 = c(1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 2, 1), 
    X5 = c(1, 0, 0, 0, 0, 2, 2, 2, 2, 2, 0, 1, 2, 2), X6 = c(2, 
    2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 1, 2, 2), X7 = c(2, 2, 2, 2, 
    2, 2, 2, 2, 1, 1, 0, 2, 2, 2), X8 = c(1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 2, 1), X9 = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 
    1, 1, 0, 2), X10 = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 2, 
    1, 2), X11 = c(2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 1, 2, 2), 
    X12 = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 0, 1, 0, 1, 2), X13 = c(2, 
    2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 1, 0, 2), X14 = c(0, 0, 0, 
    0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1), X15 = c(0, 0, 0, 0, 0, 
    0, 0, 0, 0, 0, 0, 1, 0, 0), X16 = c(1, 1, 0, 0, 0, 1, 1, 
    1, 1, 1, 0, 2, 1, 1), X17 = c(2, 2, 2, 2, 2, 1, 1, 1, 1, 
    1, 0, 2, 1, 1), X18 = c(2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 1, 
    1, 0, 1), X19 = c(2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 0, 1, 
    0), X20 = c(2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 1, 1, 0, 0), X21 = c(1, 
    1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1), X22 = c(0, 0, 0, 
    0, 0, 1, 1, 1, 1, 1, 0, 2, 0, 1), X23 = c(1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 2, 0, 1, 1), X24 = c(1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 0, 1, 2, 1), X25 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 
    0, 1, 0, 2, 0), X26 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 
    0, 2, 1)), row.names = c("S1", "S2", "S3", "S4", "S5", "S6", 
"S7", "S8", "S9", "S10", "S11", "S12", "S13", "S14"), class = "data.frame")

I looks like that :

   group X1 X2 X3 X4
S1    g1  0  1  1  1
S2    g1  0  1  1  1
S3    g1  0  1  1  1
S4    g1  0  1  1  0
S5    g1  0  1  1  0

I want to create a list of dataframes based on the unique values of myd$group which are 3 (g1,g2,g3) so every element of a list will be a subset of myd dataframe with unique values of myd$group. I know how to do it using a for loop but I think for loops in R are slow, please correct me if I am wrong about that. Thus a solution with some apply family or dplyr package would be very welcome.

0

1 Answer 1

3

We can use split to create a list of data.frames

lst1 <- split(myd, myd$group)

In tidyverse, it can be

library(dplyr)
myd %>%
   group_split(group)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.