des*_*hen 5 r correlation tidyverse
我想获得 tidyverse 中多个变量的相关矩阵。但是,我想按另一列进行分组。例如,假设我有一个df包含列的数据框,我想按年份year查看V1、V2、之间的相关性。V3
year V1 V2 V3 misc_var
2018 5 6 5 a
2018 4 6 4 b
2018 3 2 3 NA
2013 5 8 2 4
2013 6 3 8 8
2013 4 7 5 NA
Run Code Online (Sandbox Code Playgroud)
我尝试过某事。沿着
cor_output = df %>%
group_by(year) %>%
select(V1, V2, V3, year) %>%
cor(use = "pairwise.complete.obs")
Run Code Online (Sandbox Code Playgroud)
但是,它不是计算每年从 V1 到 V3 的相关性,而是只是将year变量添加到相关性中。
所需的输出应该如下所示(请注意输出中的相关性是组成的)
year var V1 V2 V3
2013 V1 1 0.7 0.3
2013 V2 ... 1 ...
...
...
2018 V2 0.6 1 0.7
...
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
corrr一种方法是将包与以下命令结合使用purrr::nest():
library(tidyverse)
library(corrr)
df <- tribble(
~year, ~V1, ~V2, ~V3, ~misc_var,
2018, 5, 6, 5, "a",
2018, 4, 6, 4, "b",
2018, 3, 2, 3, NA,
2013, 5, 8, 2, "4",
2013, 6, 3, 8, "8",
2013, 4, 7, 5, NA
)
df %>%
select_if(is.numeric) %>%
group_by(year) %>%
nest() %>%
mutate(
correlations = map(data, correlate)
) %>%
unnest(correlations)
#>
#> Correlation method: 'pearson'
#> Missing treated using: 'pairwise.complete.obs'
#>
#>
#> Correlation method: 'pearson'
#> Missing treated using: 'pairwise.complete.obs'
#> # A tibble: 6 x 5
#> year rowname V1 V2 V3
#> <dbl> <chr> <dbl> <dbl> <dbl>
#> 1 2018 V1 NA 0.866 1
#> 2 2018 V2 0.866 NA 0.866
#> 3 2018 V3 1 0.866 NA
#> 4 2013 V1 NA -0.756 0.5
#> 5 2013 V2 -0.756 NA -0.945
#> 6 2013 V3 0.5 -0.945 NA
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用以下更具实验性的group_map或group_modify功能dplyr:
df %>%
select_if(is.numeric) %>%
group_by(year) %>%
group_map(~ correlate(.x)) # or group_modify(~ correlate(.x))
Run Code Online (Sandbox Code Playgroud)