使用spearman测试,R组中的两组相关

时间:2018-05-25 12:14:14

标签: r dataframe dplyr plyr

在我的数据集中,我必须按组执行相关

我写

require(plyr)
func <- function(terr)
{
  return(data.frame(COR = cor(terr$Killed, terr$Terr..Attacks,terr$GDP.capita)))
}

ddply(terr, .(Macro.Region,Religion), func)

然后我收到了错误

Error in cor(terr$Killed, terr$Terr..Attacks, terr$GDP.capita) : 
  invalid 'use' argument

出了什么问题,如何纠正执行分析

terr=structure(list(Macro.Region = structure(c(5L, 4L, 4L, 3L, 4L, 
6L, 1L, 2L, 4L, 3L, 6L, 5L, 4L, 4L, 3L, 4L, 6L, 1L, 2L, 4L, 3L, 
6L), .Label = c("Arab Countries", "Asia", "Eastern Europe and post-Soviet", 
"Latin America", "Sub-Saharan Africa", "Western States"), class = "factor"), 
    Killed = c(0L, 0L, 0L, 6L, 0L, 0L, 1L, 76L, 0L, 0L, 36L, 
    0L, 0L, 0L, 6L, 0L, 0L, 1L, 76L, 0L, 0L, 36L), Terr..Attacks = c(2L, 
    0L, 2L, 2L, 0L, 9L, 3L, 88L, 0L, 0L, 6L, 2L, 0L, 2L, 2L, 
    0L, 9L, 3L, 88L, 0L, 0L, 6L), Religion = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 2L, 2L, 1L, 1L, 1L), .Label = c("Christianity", "Islam"
    ), class = "factor"), GDP.capita = c(6813L, 26198L, 20677L, 
    9098L, NA, 49882L, 51846L, 4207L, 17508L, 18616L, 46301L, 
    6813L, 26198L, 20677L, 9098L, NA, 49882L, 51846L, 4207L, 
    17508L, 18616L, 46301L)), class = "data.frame", row.names = c(NA, 
-22L))

这里的解决方案spearman correlation by group in R不合适,因为我有两个小组和三个大战

1 个答案:

答案 0 :(得分:1)

您可以尝试tidyverse使用purrr函数keep来限制具有足够样本大小的组和map来计算成对相关性。

library(tidyverse)
terr %>% 
 split(list(.$Macro.Region, .$Religion)) %>% 
 keep(~nrow(.) > 3) %>% 
 map(~.x %>% 
         select(Killed,GDP.capita,Terr..Attacks) %>% 
         cor(cbind.data.frame(.), use = "complete.obs"))
$`Eastern Europe and post-Soviet.Christianity`
              Killed GDP.capita Terr..Attacks
Killed             1         -1             1
GDP.capita        -1          1            -1
Terr..Attacks      1         -1             1

$`Latin America.Christianity`
              Killed GDP.capita Terr..Attacks
Killed            NA         NA            NA
GDP.capita        NA  1.0000000    -0.1543897
Terr..Attacks     NA -0.1543897     1.0000000

$`Western States.Christianity`
              Killed GDP.capita Terr..Attacks
Killed             1         -1            -1
GDP.capita        -1          1             1
Terr..Attacks     -1          1             1

尝试Hmisc的{​​{1}}函数来检索相应的pvalues

rcorr