This question has been partially answered previously (e.g., here), but – as far as I can tell – there is no full answer using a reproducible example. I would like to select variables by name from a nested data frame, calculate pairwise correlations, and then add the correlation coefficients and p-values to the unnested data frame with appropriately names columns. The following example yields the desired outcome:
library(tidyverse)
library(broom)
df <- mtcars %>%
nest(data = everything()) %>%
mutate(cor_test = map(data, ~ cor.test(.x$mpg, .x$disp)),
tidied = map(cor_test, tidy)) %>%
unnest(tidied) %>%
select(-c(cor_test, statistic, parameter, conf.low, conf.high, method, alternative)) %>%
rename(c(mpg_disp_estimate = estimate, mpg_disp_p.value = p.value)) %>%
mutate(cor_test = map(data, ~ cor.test(.x$mpg, .x$cyl)),
tidied = map(cor_test, tidy)) %>%
unnest(tidied) %>%
select(-c(cor_test, statistic, parameter, conf.low, conf.high, method, alternative)) %>%
rename(c(mpg_cyl_estimate = estimate, mpg_cyl_p.value = p.value)) %>%
mutate(cor_test = map(data, ~ cor.test(.x$disp, .x$cyl)),
tidied = map(cor_test, tidy)) %>%
unnest(tidied) %>%
select(-c(cor_test, statistic, parameter, conf.low, conf.high, method, alternative)) %>%
rename(c(disp_cyl_estimate = estimate, disp_cyl_p.value = p.value))
Obviously, this is not a good solution, since it involves repeating the same code over and over again. Is there a way to accomplish this goal more elegantly with purrr
and broom
?