首页 > 解决方案 > 将 cor.test 的意义转化为向量

问题描述

我有一个 data.table 如下:

library(data.table)

DT <- fread(
"ID country year Event_A Event_B
4   BEL   2002  0   1
5   BEL   2002  0   1
6   NLD   2002  1   1
7   NLD   2006  1   0
8   NLD   2006  1   1
9   GBR   2001  0   1
10  GBR   2001  0   0
11  GBR   2001  0   1
12  GBR   2007  1   1
13  GBR   2007  1   1",
header = TRUE)

我可以Event_A通过执行以下操作来获得与其他数值列的相关性:

numcols <- names(Filter(is.numeric,DT)) 
corr_y <- DT[, data.table(var=numcols, cor(.SD[, mget(numcols)], .SD[, mget("Event_A")],use= 
"pairwise.complete.obs", method= "pearson"))]

但是,我也希望有一个具有sign_corr_y相关性意义的向量,例如 。

我知道这cor.test很重要,但以下不起作用:

sign_corr_y<- DT[, data.table(var=numcols, cor.test(.SD[, mget(numcols)], .SD[, mget("Event_A")],use= "pairwise.complete.obs", method= "pearson"))]

给出错误:Error in cor.test.default(.SD[, mget(numcols)], .SD[, mget("Event_A")], : 'x' and 'y' must have the same length

这也不起作用:

sign_corr_y<- DT[, data.table(var=numcols, cor.test$p.value(.SD[, mget(numcols)], .SD[, mget("Event_A")],use= "pairwise.complete.obs", method= "pearson"))]

我看过他们在这里做了什么,但我不知道如何将它们合并unlist到我的 data.table 解决方案中。

有人可以帮忙吗?

编辑:我的实际数据仍然出现错误(在函数内部使用):

根据@IceCreamToucan 的回答,我尝试过:

  corr_y_sign <- DT[, data.table(var=numcols, sapply(Filter(is.numeric, DT), function(x) cor.test(x, DT[, mget(corvar)], use= "pairwise.complete.obs", method= "pearson")$p.value))]
  corr_y_sign <- sapply(Filter(is.numeric, DT), function(x) cor.test(x, DT[, mget(corvar)], use= "pairwise.complete.obs", method= "pearson")$p.value)

但我总是得到错误:Error in cor.test.default(x, DT[, mget(corvar)], use = "pairwise.complete.obs", : 'x' and 'y' must have the same length

标签: rdata.tablecorrelation

解决方案


推荐阅读