David Z
David Z

Reputation: 7041

Why do.call rbind outputs only one row?

I have a similar situation like this:

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

I'm wondering why it's not an output as I expected:

    output
          [,1]   [,2]
    [1,] 1.066 0.3019
    [2,] 0.00011 1

Upvotes: 0

Views: 185

Answers (3)

James
James

Reputation: 66834

2 issues: you are looping over y1 twice, and you are not appending your new result to the older one. I think you want to loop using lapply and rbind that list:

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

Upvotes: 1

Roland
Roland

Reputation: 132706

You basically do this twice:

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

See how there is only one element in the list? This element is passed to rbind:

do.call(rbind, myList)
#         [,1]    [,2]
#[1,] 1.065739 0.30191

rbind(myList[[1]])
#         [,1]    [,2]
#[1,] 1.065739 0.30191

Upvotes: 0

Miff
Miff

Reputation: 7941

In each iteration of the loop (you've used y1 twice) output is overwritten by a new value. Presumably you were aiming for soemthing like:

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

Upvotes: 3

Related Questions