首页 > 解决方案 > R 错误(fisher 测试):x 的所有条目必须是非负且有限的

问题描述

下面是我的代码:

 d2 <- data.frame(cbind(1:10, sapply(1:4, function(x) { sample(1:25, size = 10, replace = TRUE) })))

 pvals <- rep(0, nrow(d2))

 for (n in 1:nrow(d2)) 
  {
  pvals[n] <- fisher.test(
    matrix(d2[n, 2:5], nrow = 2, ncol = 2, byrow = TRUE)
  )$p.value
  }

我的错误在哪里?谢谢!

标签: r

解决方案


在 OP 的代码中,我们需要在创建之前将结构unlist取消列表,因为每行提取都是data.framevectormatrixdata.frame

str(d2[1, 2:5])
#'data.frame':  1 obs. of  4 variables:
# $ X2: int 22
# $ X3: int 12
# $ X4: int 19
# $ X5: int 12

这会list在我们调用时创建matrix

str(matrix(d2[1, 2:5], 2, 2))
#List of 4
# $ : int 22
# $ : int 12
# $ : int 19
# $ : int 12
# - attr(*, "dim")= int [1:2] 2 2

如果我们unlist,结构变成

str(matrix(unlist(d2[1, 2:5]), 2, 2))
#int [1:2, 1:2] 22 12 19 12

在 OP 的代码中进行更改

pvals <- rep(0, nrow(d2))
for (n in 1:nrow(d2)) {
   pvals[n] <- fisher.test(
      matrix(unlist(d2[n, 2:5]), nrow = 2, ncol = 2, byrow = TRUE)
     )$p.value
  }

pvals
#[1] 0.80226381499 0.09361771430 0.23302332741 0.00001155306 0.76106849673 0.81049227216 0.14211831663 0.28974696874 0.00140855512
#[10] 0.04810238920

另一个选项是apply,我们指定MARGIN = 1for rowwise 循环

apply(d2[-1], 1, FUN = function(x) fisher.test(matrix(x, 2, 2, byrow = TRUE))$p.value)
#[1] 0.80226381499 0.09361771430 0.23302332741 0.00001155306 0.76106849673 0.81049227216 0.14211831663 0.28974696874 0.00140855512
#[10] 0.04810238920

推荐阅读