我有类似的情况:
set.seed(2014)
df<-data.frame(
group=rbinom(100,1,0.6),
y1=rbinom(100,1,0.3),
y2=rbinom(100,1,0.8))
for (y in c("y1","y1")){
test<-summary(table(df[,"group"],df[,y]))
output<-do.call(rbind,list(cbind(test$statistic,test$p.value)))
}
output
[,1] [,2]
[1,] 1.066 0.3019
我想知道为什么它不像我预期的那样输出:
output
[,1] [,2]
[1,] 1.066 0.3019
[2,] 0.00011 1
答案 0 :(得分:3)
在循环的每次迭代中(您已经使用y1两次)输出被新值覆盖。大概你的目标就是:
set.seed(2014)
df<-data.frame(
group=rbinom(100,1,0.6),
y1=rbinom(100,1,0.3),
y2=rbinom(100,1,0.8))
output <- NULL
for (y in c("y1","y2")){
test<-summary(table(df[,"group"],df[,y]))
output<-rbind(output,cbind(test$statistic,test$p.value))
}
output
答案 1 :(得分:1)
2个问题:您正在循环y1两次,并且您没有将新结果附加到较旧的结果。我想你想使用列出的lapply
和rbind
循环:
do.call(rbind,lapply(c("y1","y2"),
function (y) summary(table(df[,"group"],df[,y]))))[,c("statistic","p.value")]
statistic p.value
[1,] 1.065739 0.30191
[2,] 0.000106695 0.9917585
答案 2 :(得分:0)
你基本上这样做了两次:
y <- "y1"
test<-summary(table(df[,"group"],df[,y]))
myList <- list(cbind(test$statistic,test$p.value))
#[[1]]
# [,1] [,2]
#[1,] 1.065739 0.30191
查看列表中只有一个元素?此元素将传递给rbind
:
do.call(rbind, myList)
# [,1] [,2]
#[1,] 1.065739 0.30191
rbind(myList[[1]])
# [,1] [,2]
#[1,] 1.065739 0.30191