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

How may I run fisher.test within ddply?

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 值。

您可以使用 splitsapply 在 base R 中执行此操作:

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