I'm trying to split a dataframe based on values in the id
column.
what I have:
ids<-as.data.frame(c("a","a","a","b","b","b","c","c","c"))
unique_id<-unique(ids)
values<-as.data.frame(rep(1:3,3))
df<-as.data.frame(cbind(ids,values))
colnames(df)<-c("id","values")
and it looks like:
> df
id values
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
the code and error I'm getting is:
> for(id in unique_id){
+ paste0("value_for_",id)<-split(df, id = df$id)
+ }
Error in deparse(...) :
unused argument (id = c(1, 1, 1, 2, 2, 2, 3, 3, 3))
what I want:
value_for_a
id value
a 1
a 2
a 3
value_for_b
id value
b 1
b 2
b 3
value_for_c
id value
c 1
c 2
c 3
I feel this should be fairly straightforward, but I'm fresh out of ideas. I am not opposed to using more sophisticated methods than a for loop
.
You can use nest()
for this.
library(tidyr)
df%>%
group_by(id)%>%
nest()
# A tibble: 3 x 2
id data
<fctr> <list>
1 a <tibble [3 x 1]>
2 b <tibble [3 x 1]>
3 c <tibble [3 x 1]>
Each tibble contains the values you're interested in.
df%>%
group_by(id)%>%
nest()%>%
.$data
[[1]]
# A tibble: 3 x 1
values
<int>
1 1
2 2
3 3
[[2]]
# A tibble: 3 x 1
values
<int>
1 1
2 2
3 3
[[3]]
# A tibble: 3 x 1
values
<int>
1 1
2 2
3 3
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments