从cor.test的意义转化为向量

时间:2019-12-23 13:32:37

标签: r data.table correlation

我有一个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"))]

我已经查看了他们所做的here,但是我不知道如何将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

0 个答案:

没有答案