Adam Waring
Adam Waring

Reputation: 1268

R data.table assign multiple columns from list output

x = data.table(group=c("a", "b"), x1=c(9, 4), x2=c(2, 7), ss1=c(20, 20), ss2=c(20, 20))
x[,fisher.test(rbind(c(x1, ss1), c(x2, ss2)))[1:3], by=group]

Calculating a fisher.test per group and taking the first three elements of the output generates three named columns for p.value, conf.int and estimate. This is great except it takes only the lower confidence interval and not the upper from the second list item in the Fisher output.

For some reason, I cannot recreate this behaviour when trying to get both the upper and lower CIs.

If you unlist this output it gives all four values, but in a single column V1.

x[,unlist(fisher.test(rbind(c(x1, ss1), c(x2, ss2)))[1:3]), by=group]

Any combination of unlisting, relisting, naming etc. do not seem to give me the required output.

This is a recurring problem for me so would be great to get an answer!

Upvotes: 3

Views: 60

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24770

It's kind of silly, but you could use as.list:

library(data.table)
x[,as.list(unlist(fisher.test(rbind(c(x1, ss1), c(x2, ss2)))[1:3])), by=group]
   group            p.value         conf.int1        conf.int2 estimate.odds ratio
1:     a 0.0877372116511888 0.766153560249588  46.677263221989    4.37927894874589
2:     b  0.507673628580576 0.106483621566036 2.70725328753808   0.577676599291802

Upvotes: 3

Related Questions