I need to turn a (working) bit of dplyr/broom code into a function, since I'll call it several (dozen) times.
I am stuck -- and this has likely to do with Non Standard Evaluation being mixed with Standard Evaluation.
Here I take code directly from the vignette 'broom and dplyr'
library(tidyverse)
library(broom)
data(Orange)
Orange %>%
nest(-Tree) %>%
mutate(
test = map(data, ~ cor.test(.x$age, .x$circumference)),
tidied = map(test, tidy)
) %>%
unnest(tidied, .drop = TRUE)
This works:
Tree estimate statistic p.value parameter conf.low conf.high method alternative
1 1 0.9854675 12.97258 4.851902e-05 5 0.9012111 0.9979400 Pearson's product-moment correlation two.sided
2 2 0.9873624 13.93129 3.425041e-05 5 0.9136142 0.9982101 Pearson's product-moment correlation two.sided
3 3 0.9881766 14.41188 2.901046e-05 5 0.9189858 0.9983260 Pearson's product-moment correlation two.sided
4 4 0.9844610 12.53575 5.733090e-05 5 0.8946782 0.9977964 Pearson's product-moment correlation two.sided
5 5 0.9877376 14.14686 3.177093e-05 5 0.9160865 0.9982635 Pearson's product-moment correlation two.sided
Now the point is that I want to make a function out of it.
So if I try this:
afunction <- function(data, var) {
data %>%
nest(-Tree) %>%
mutate(
test = map(data, ~ cor.test(.x$age, .x$var)), # S3 list-col
tidied = map(test, tidy)
) %>%
unnest(tidied, .drop = TRUE)
}
It fails miserably.
Error in cor.test.default(.x$age, .x$var) : 'x' and 'y' must have the same length
I have tried to use NSE, quotation, semiquotation. I admit I tried a bit at random since I cannot find a proper tutorial of how to let NSE and SE play nicely together with the $ operator.
Any solutions -- especially one that would scale & teach me how to solve these issues once and for all? I am also happy for pointers at relevant books / tutorials.