在 for 循环中 dcast 多个数据帧

dcast multiple dataframes in a for loop

所以我有多个数据框,遵循以下模式:

df1<-data.frame(id=c("1","2","1","2"),choice=c(1,1,1,2))
df2<-data.frame(id=c(...),choice=c(...))
df1
  id choice
1  1      1
2  2      1
3  1      1
4  2      2

现在我想知道,每个人选择不同选项的频率是多少:

df1_cast<-dcast(df1,choice~id,value.var = "choice",fill = 0,fun.aggregate = length)
df1_cast
  choice 1 2
1      1 2 1
2      2 0 1

因为我有多个数据帧,所以我尝试用 for 循环循环它:

experiments<-list(df1,df2,...)
for (i in 1:length(experiments)){
  dcast(experiments[i],choice~id,value.var="choice",fill=0,fun.aggregate=length)

}

遗憾的是,数据帧保存为列表中的列表,dcast 函数找不到 value.var

您可以使用 lapply:

df1<-data.frame(id=c("1","2","1","2"),choice=c(1,1,1,2))
df2<-data.frame(id=c("1","2","1","2"),choice=c(2,2,2,1))
experiments<-list(df1,df2)

library(reshape2)

lapply(experiments, function(dfx) 
                     dcast(dfx,choice~id,value.var = "choice", 
                               fill = 0,fun.aggregate = length))

#> [[1]]
#>   choice 1 2
#> 1      1 2 1
#> 2      2 0 1
#> 
#> [[2]]
#>   choice 1 2
#> 1      1 0 1
#> 2      2 2 1