set.seed(123)
df <- data.frame(group = rep(c("G1", "G2"), each = 10),
var1 = rnorm(20),
var2 = rnorm(20))
library(tidyverse)
library(broom)
df %>%
group_by(group) %>%
summarize(correlation = cor(var1, var2,, method = "sp"))
# A tibble: 2 x 2
group correlation
<fct> <dbl>
1 G1 -0.200
2 G2 0.0545
# with pvalues and further stats
df %>%
nest(-group) %>%
mutate(cor=map(data,~cor.test(.x$var1, .x$var2, method = "sp"))) %>%
mutate(tidied = map(cor, tidy)) %>%
unnest(tidied, .drop = T)
# A tibble: 2 x 6
group estimate statistic p.value method alternative
<fct> <dbl> <dbl> <dbl> <chr> <chr>
1 G1 -0.200 198 0.584 Spearman's rank correlation rho two.sided
2 G2 0.0545 156 0.892 Spearman's rank correlation rho two.sided