gpt4 book ai didi

r - 在 for 循环中 dcast 多个数据帧

转载 作者:行者123 更新时间:2023-12-04 11:37:00 25 4
gpt4 key购买 nike

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

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

关于r - 在 for 循环中 dcast 多个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com