2017-04-16 48 views
0
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如何在ddply中運行fisher.test?

+0

是'df.agg [ - 2]'應該是'D'或' d [ - 2]'? – r2evans

+0

是的,我很抱歉的錯誤。 –

+0

錯誤消息非常多地解釋它。您至少需要兩行和兩列才能工作,但只有一行「topic」是「b」。 – AkselA

回答

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