r - 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
}
我的错误在哪里?谢谢!
解决方案
在 OP 的代码中,我们需要在创建之前将结构unlist
取消列表,因为每行提取都是data.frame
vector
matrix
data.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 = 1
for 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
推荐阅读
- sql - 优化 sum() over(order by...) 子句抛出“超出资源”错误
- xpath - 将 text() 添加到我的 XPath 时,结果的数量是重复的。为什么?
- visual-studio-code - 如何设置 VSCode 以不将花括号放在新行上?
- vba - 如何阻止记录在关闭时被覆盖
- bash - 使用 sed 在文件开头添加多行变量
- azure - Terraform Azure:从自定义映像配置 VM 时如何配置数据磁盘类型
- tfs - TFS 如何构建基于 Visual Studio 的“打开文件夹”CMake 项目
- xpages - 未找到 Domino 9 更新站点 osgi 类
- azure-devops - 查询状态类别
- javascript - 如何访问内部 HTML 中的特定元素?