假设我想要行为相关矩阵
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)
怎么办?
使用tidyverse的解决方案.我们可以将数据帧转换为长格式,使用创建列表列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)
现在我们可以使用mutate和case_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)