我如何运行多变量相关?
How do I run multivariable correlation?
我有大量数据想除以多个变量,如下图所示:
这里一共有63个地块,除以3个变量(rows
、cols
和fram
)。当然,实际上 valuex
和 valuey
有 3 个以上的观察值。我想尽可能高效地找到其中每一个的 Pearson 相关性,但我的想法有点空白。
下面是创建图表的一些示例数据:
example_df <- data.frame(rows = rep(c('r1', 'r2', 'r3'), 63),
cols = rep(letters[1:7], 27),
fram = rep(c('X', 'Y', 'Z'), each = 63),
valuex = rnorm(189),
valuey = rnorm(189))
您可以使用 dplyr
到 group_by
多个变量,然后 summarize
为每个子组获取 valuex
和 valuey
之间的 cor
:
library(dplyr)
example_df %>% group_by(rows, cols, fram) %>% summarize(cor = cor(valuex, valuey))
#> # A tibble: 63 x 4
#> # Groups: rows, cols [21]
#> rows cols fram cor
#> <chr> <chr> <chr> <dbl>
#> 1 r1 a X -0.709
#> 2 r1 a Y 0.178
#> 3 r1 a Z -0.597
#> 4 r1 b X -0.338
#> 5 r1 b Y 0.981
#> 6 r1 b Z -0.731
#> 7 r1 c X 0.945
#> 8 r1 c Y -0.913
#> 9 r1 c Z 0.177
#> 10 r1 d X 0.999
#> # ... with 53 more rows
由 reprex package (v0.3.0)
于 2020 年 7 月 14 日创建
我有大量数据想除以多个变量,如下图所示:
这里一共有63个地块,除以3个变量(rows
、cols
和fram
)。当然,实际上 valuex
和 valuey
有 3 个以上的观察值。我想尽可能高效地找到其中每一个的 Pearson 相关性,但我的想法有点空白。
下面是创建图表的一些示例数据:
example_df <- data.frame(rows = rep(c('r1', 'r2', 'r3'), 63),
cols = rep(letters[1:7], 27),
fram = rep(c('X', 'Y', 'Z'), each = 63),
valuex = rnorm(189),
valuey = rnorm(189))
您可以使用 dplyr
到 group_by
多个变量,然后 summarize
为每个子组获取 valuex
和 valuey
之间的 cor
:
library(dplyr)
example_df %>% group_by(rows, cols, fram) %>% summarize(cor = cor(valuex, valuey))
#> # A tibble: 63 x 4
#> # Groups: rows, cols [21]
#> rows cols fram cor
#> <chr> <chr> <chr> <dbl>
#> 1 r1 a X -0.709
#> 2 r1 a Y 0.178
#> 3 r1 a Z -0.597
#> 4 r1 b X -0.338
#> 5 r1 b Y 0.981
#> 6 r1 b Z -0.731
#> 7 r1 c X 0.945
#> 8 r1 c Y -0.913
#> 9 r1 c Z 0.177
#> 10 r1 d X 0.999
#> # ... with 53 more rows
由 reprex package (v0.3.0)
于 2020 年 7 月 14 日创建