我的数据框看起来像这样:

595.00000    18696      984.00200     32185    Group1   
935.00000    18356      1589.00000    31580    Group2             
40.00010     19251      73.00000      33096    Group3             
1058.00000   18233      1930.00000    31239    Group4                 
19.00000     19272      27.00000      33142    Group5             
1225.00000   18066      2149.00000    31020    Group6   
....                  

对于每个组,我都想做 Fisher 精确检验。
table <- matrix(c(595.00000, 984.00200, 18696, 32185), ncol=2, byrow=T)   
Group1 <- Fisher.test(table, alternative="greater") 

尝试使用以下方法循环数据框:
for (i in 1:nrow(data.frame))   
 {   
 table= matrix(c(data.frame$V1, data.frame$V2, data.frame$V3, data.frame$V4), ncol=2, byrow=T)     
fisher.test(table, alternative="greater")   
} 

但收到错误信息
Error in fisher.test(table, alternative = "greater") :   
FEXACT error 40.   
Out of workspace.   
In addition: Warning message:   
In fisher.test(table, alternative = "greater")  :   
'x' has been rounded to integer: Mean relative difference: 2.123828e-06 

我怎样才能解决这个问题,或者可以用另一种方式循环数据?

请您参考如下方法:

您的第一个错误是:Out of workspace

?fisher.test 
fisher.test(x, y = NULL, workspace = 200000, hybrid = FALSE, 
        control = list(), or = 1, alternative = "two.sided", 
        conf.int = TRUE, conf.level = 0.95, 
        simulate.p.value = FALSE, B = 2000) 

您应该尝试增加 workspace (默认值 = 2e5)。

但是,在您的情况下会发生这种情况,因为您拥有非常大的值(value)。根据经验,如果矩阵的所有元素都 > 5(或在您的情况下为 10,因为 d.f. = 1),那么您可以使用 chisq.test 安全地通过独立性卡方检验来近似它.对于您的情况,我认为您应该使用 chisq.test .

warning message发生是因为您的值不是整数 (595.000) 等。所以,如果您真的想使用 fisher.test递归地,这样做(假设您的数据在 df 中并且是 data.frame :
# fisher.test with bigger workspace 
apply(as.matrix(df[,1:4]), 1, function(x)  
         fisher.test(matrix(round(x), ncol=2), workspace=1e9)$p.value) 

或者,如果您更愿意用 chisq.test 代替(我认为你应该为这些巨大的性能增益值而没有 p 值的显着差异):
apply(as.matrix(df[,1:4]), 1, function(x)  
         chisq.test(matrix(round(x), ncol=2))$p.value) 

这将提取 p 值。

编辑 1:我刚刚注意到你使用 one-sided Fisher's exact test .也许您应该继续使用具有更大工作空间的 Fisher 检验,因为我不确定是否有独立性的单边卡方检验,因为它已经从 right-tail 计算出来的。概率(并且您不能将 p 值除以 2,因为它是不对称的)。

编辑 2:由于您需要带有 p 值的组名并且您已经有一个 data.frame,我建议您使用 data.table包装如下:
# example data 
set.seed(45) 
df <- as.data.frame(matrix(sample(10:200, 20), ncol=4)) 
df$grp <- paste0("group", 1:nrow(df)) 
# load package 
require(data.table) 
dt <- data.table(df, key="grp") 
dt[, p.val := fisher.test(matrix(c(V1, V2, V3, V4), ncol=2),  
                workspace=1e9)$p.value, by=grp] 
> dt 
#     V1  V2  V3  V4    grp        p.val 
# 1: 130  65  76  82 group1 5.086256e-04 
# 2:  70  52 168 178 group2 1.139934e-01 
# 3:  55 112 195  34 group3 7.161604e-27 
# 4:  81  43  91  80 group4 4.229546e-02 
# 5:  75  10  86  50 group5 4.212769e-05 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!