我正在尝试运行rcorr
作为多个数据帧函数的一部分,为每个测试提取 p 值,但在管道输入 rcorr
时收到 NA 值。
例如,如果我创建一个矩阵并运行 rcorr
在此矩阵上,使用 $P
提取 pvalue 表和 p 值 [2]
它有效...
library(Hmisc)
library(magrittr)
mt <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ncol=2)
rcorr(mt, type="pearson")$P[2]
[1] 0
但是如果我尝试通过管道传递它,我只会收到 NA。
mt %>% rcorr(., type="pearson")$P[2]
[1] NA NA
mt %>% rcorr(., type="pearson")$P
Error in .$rcorr(., type = "pearson") :
3 arguments passed to '$' which requires 2
有人可以向我解释为什么这不起作用或提供解决方法吗?理想情况下,我不想在运行 rcorr
之前为每个矩阵创建变量
提前致谢。
最佳答案
解决方案
(mt %>% mcor(type = "pearson"))$P[2]
# [1] 0
说明
请注意,两者
mt %>% rcorr(., type = "pearson")
和
mt %>% rcorr(type = "pearson")
按预期工作。问题是您将 $
和 [
添加到第二个对象,这基本上就像后续的函数调用一样。例如,
s <- function(x) c(1, 1 + x)
1 %>% s
# [1] 1 2
按预期工作,但是
1 %>% s[1]
# Error in .[s, 1] : incorrect number of dimensions
不会返回 1
,因为我们正在尝试执行类似 s[1](1)
的操作。
现在
1 %>% s(x = .)[1]
# Error in .[s(x = .), 1] : incorrect number of dimensions
就像你的一样
mt %>% rcorr(., type = "pearson")$P[2]
# [1] NA NA
比较棘手。请注意,它可以重写为
mt %>% `[`(`$`(rcorr(., type = "pearson"), "P"), 2)
# [1] NA NA
所以,现在很明显后者不起作用,因为它基本上是
`[`(mt, `$`(rcorr(mt, type = "pearson"), "P"), 2)
# [1] NA NA
破译后,是
mt[rcorr(mt, type = "pearson")$P, 2]
# [1] NA NA
关于r - 通过管道输入 rcorr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233231/