使用tidyverse 的解决方案。我们可以将数据框转换为长格式,使用nest创建列表列,然后使用map对每个子集执行cor.test。之后,map_dbl 可以通过指定名称"p.value" 来提取 P 值。 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
如果您不需要列表列,可以使用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
现在我们可以使用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