我如何在ddply中运行fisher.test?

时间:2017-04-16 22:23:15

标签: r plyr chi-squared

d <- data.frame(topic=c("a","a","a","b","c","c"), year=c(2001,2002,2004,2003,2011,2012),
                I=c(3,2,4,3,0,1), II=c(2,1,2,3,4,0), III=c(0,0,1,2,3,0))
library(plyr)
chip <- ddply(df.agg[,-2], "topic", function(x){
    round(fisher.test(x[,-1])$p.value, 3)
  })
#Error in fisher.test(x[, -1]) : 'x' must have at least 2 rows and columns

如何在ddply中制作fisher.test?我希望一行的主题(例如b)具有NA值,但其他行报告p值。

1 个答案:

答案 0 :(得分:0)

您可以在基座R中使用splitsapply

执行此操作
sapply(split(d, d$topic), function(i) 

  if (nrow(i) == 1) {

    NA

  } else {

    round(fisher.test(i[,3:5])$p.value, 3)

})

结果:

    a     b     c 
1.000    NA 0.125