'How do I create a list containing new data frames from an existing data frame?
I have a csv file containing 5 columns, 225 rows containing my data. The columns pertain to the experiments' Subject_ID, treatment (9 types), replicate(5), time (5) and output. I would like to organize my data such new data frames are created according to the treatment and have the data frames stored within a list.
Here is an example of the table:
Subject ID | Treatment | Replicate | Time | Output |
---|---|---|---|---|
Human 1 | a | 1 | 0 | y1 |
Human 2 | b | 1 | 0 | y2 |
Human 1 | b | 2 | 2 | y3 |
Human 2 | a | 2 | 2 | y4 |
This is my code:
df$Strain<- as.character(df$Subject_ID)
df$Time<- as.character(df$Time)
df$Replicate<- as.character(df$Replicate)
#Create a list of new data frames by treatments
Treatments.list <- list()
for (i in 1:length(unique(df$Treatment))) {
Treatments <- filter(df, Treatment == i)
Treatments.list [[i]] <- cbind.data.frame(Treatments[1:5])
}
My problem with this code is that the list that is returned is a list of 9 (which is correct) with all of the columns, but they are empty. How do I fix this?
Also I have tried:
for (i in (unique(df$Treatment))
instead of the one above and it works, however, the i only returns one value of the treatments, instead of 9.
Thanks for the help in advance!
Solution 1:[1]
df=read.table(text="
Subject ID Treatment Replicate Time Output
Human 1 a 1 0 y1
Human 2 b 1 0 y2
Human 1 b 2 2 y3
Human 2 a 2 2 y4",h=T)
split(df,df$Treatment)
which results in
$a
Subject ID Treatment Replicate Time Output
1 Human 1 a 1 0 y1
4 Human 2 a 2 2 y4
$b
Subject ID Treatment Replicate Time Output
2 Human 2 b 1 0 y2
3 Human 1 b 2 2 y3
so works for me, the result is a list with two elements.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user2974951 |