r - 通过管道输入 rcorr

标签 r

我正在尝试运行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/

相关文章:

r - 为什么在 Sweave 中使用 includegraphics 时显示文本 'pdf 2'

regex - 检索文件名的一部分

R:大型数据集(48-512 GB RAM)上的randomForest的堆栈溢出错误

r - 在 R 中使用多线程/核心以压缩形式保存对象的方法是什么?

r - 计算每行每组列的平均值

python - R 与 scikit-learn 中线性回归 R2 的交叉验证

r - 如何提取列表中的第一项(即使列表为空)

java - 降低假发的分辨率

r - 比较 dplyr 中的字符串

R:为图中的轴区域添加大括号