相关矩阵与R中的p值

D.J*_*Joe 1 r dataframe dplyr

假设我想要行为相关矩阵

library(dplyr)

data(iris)
iris %>% 
  select_if(is.numeric) %>%
  cor(y =iris$Petal.Width, method = "spearman") %>%  round(2)
Run Code Online (Sandbox Code Playgroud)

现在我们看到了

              [,1]
Sepal.Length  0.83
Sepal.Width  -0.29
Petal.Length  0.94
Petal.Width   1.00
Run Code Online (Sandbox Code Playgroud)

我希望统计显着的相关性用*表示

*<0,05
**<0,01
*** <0,001
Run Code Online (Sandbox Code Playgroud)

怎么办?

www*_*www 5

使用的解决方案.我们可以将数据帧转换为长格式,使用创建列表列nest,然后用于为每个子集map执行cor.test.之后,map_dbl可以通过指定名称来提取P值"p.value".dat1是最终的输出.

library(tidyverse)

data(iris)
dat1 <- iris %>% 
  select_if(is.numeric) %>%
  gather(Column, Value, -Petal.Width) %>%
  group_by(Column) %>%
  nest() %>%
  mutate(Cor = map(data, ~cor.test(.x$Value, .x$Petal.Width, method = "spearman"))) %>%
  mutate(Estimate = round(map_dbl(Cor, "estimate"), 2), 
         P_Value = map_dbl(Cor, "p.value"))

dat1
# # A tibble: 3 x 5
#   Column       data               Cor         Estimate  P_Value
#   <chr>        <list>             <list>         <dbl>    <dbl>
# 1 Sepal.Length <tibble [150 x 2]> <S3: htest>    0.83  4.19e-40
# 2 Sepal.Width  <tibble [150 x 2]> <S3: htest>   -0.290 3.34e- 4
# 3 Petal.Length <tibble [150 x 2]> <S3: htest>    0.94  8.16e-70
Run Code Online (Sandbox Code Playgroud)

如果您不需要列表列,则可以使用select它们删除它们.

dat1 %>% select(-data, -Cor)
# # A tibble: 3 x 3
#   Column       Estimate  P_Value
#   <chr>           <dbl>    <dbl>
# 1 Sepal.Length    0.83  4.19e-40
# 2 Sepal.Width    -0.290 3.34e- 4
# 3 Petal.Length    0.94  8.16e-70
Run Code Online (Sandbox Code Playgroud)

现在我们可以使用mutatecase_when添加标签来显示重要性.

dat2 <- dat1 %>%
  select(-data, -Cor) %>%
  mutate(Significance = case_when(
    P_Value < 0.001  ~ "*** <0,001",
    P_Value < 0.01   ~ "** <0,01",
    P_Value < 0.05   ~ "*<0,05",
    TRUE             ~ "Not Significant"
  ))
dat2
# # A tibble: 3 x 4
#   Column       Estimate  P_Value Significance
#   <chr>           <dbl>    <dbl> <chr>       
# 1 Sepal.Length    0.83  4.19e-40 *** <0,001  
# 2 Sepal.Width    -0.290 3.34e- 4 *** <0,001  
# 3 Petal.Length    0.94  8.16e-70 *** <0,001 
Run Code Online (Sandbox Code Playgroud)

  • 你也可以使用`map2``map2(iris [1:3],iris ["Petal.Width"],〜{Cor < - cor.test(.x,.y,method ="spearman"); tibble(估计= Cor $估计,PValue = Cor $ p.value)})%>%bind_rows(.id ='Column')` (3认同)
  • @ D.Joe我不知道.你能确保使用`dplyr`包中的`select`函数吗? (2认同)