I am trying to subset a data frame, where I get multiple data frames based on multiple column values. Here is my example
>df
v1 v2 v3 v4 v5
A Z 1 10 12
D Y 10 12 8
E X 2 12 15
A Z 1 10 12
E X 2 14 16
The expected output is something like this where I am splitting this data frame into multiple data frames based on column v1
and v2
>df1
v3 v4 v5
1 10 12
1 10 12
>df2
v3 v4 v5
10 12 8
>df3
v3 v4 v5
2 12 15
2 14 16
I have written a code which is working right now but don't think that's the best way to do it. There must be a better way to do it. Assuming tab
is the data.frame having the initial data. Here is my code:
v1Factors<-levels(factor(tab$v1))
v2Factors<-levels(factor(tab$v2))
for(i in 1:length(v1Factors)){
for(j in 1:length(v2Factors)){
subsetTab<-subset(tab, v1==v1Factors[i] & v2==v2Factors[j], select=c("v3", "v4", "v5"))
print(subsetTab)
}
}
Can someone suggest a better method to do the above?