当我使用data.table
要使用 cor.test 函数计算每个组的相关性,它适用于默认方法(即“pearson”),但不适用于“spearman”。我收到一个data.table
error.
library("data.table")
dd <- data.table(group=sample(letters[1:3], 50, replace=TRUE), x=rnorm(50), y=rnorm(50))
head(dd)
## group x y
## 1: c 0.1808595 2.124721051
## 2: a 0.2492086 0.112128546
## 3: b -1.6392331 -1.823208890
## 4: c 0.6605648 0.981215691
## 5: c -0.4625216 -0.008350339
## 6: b -0.2747395 1.045594928
dd[ , cor.test(x, y), by=group] # works
dd[ , cor.test(x, y, method="spearman"), by=group] # does not work
## Error in `[.data.table`(dd, , cor.test(x, y, method = "spearman"), by = group) :
## Column 2 of j's result for the first group is NULL. [...]
有谁知道如何按组使用 cor.testdata.table
这不会导致错误吗?或者,如果这不能解决data.table
完全因为它与这里的 cor.test 的本质有关,所以按组使用 Spearman cor.test 的任何其他类似的(data.frame,dplyr)方法都有效吗?
问题是因为parameter
列表结果中返回的元素cor.test
for method="spearman"
is NULL
,这会导致 data.table 崩溃。
返回的错误消息非常明确地说明了这一点:
第一组的 j 结果的第 2 列为 NULL。 [...]
只需从结果中删除第 2 列即可。
dd[ , cor.test(x, y,method="spearman")[-2], by=group]
# group statistic p.value estimate null.value alternative ...
#1: c 2060 0.6263233 0.1043478 0 two.sided ...
#2: a 262 0.5762578 -0.1909091 0 two.sided ...
#3: b 650 0.5667271 -0.1607143 0 two.sided ...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)