1

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.

PaoloCrosetto
  • 600
  • 1
  • 7
  • 16
  • `$` and `cor.test` come from base R so they won't work with NSE, see `help('$')` for more info. To solve your problem, just change `.x$var` with `.x[[var]]` then call your function using `afunction(Orange, "circumference")` – A. Suliman Jun 18 '19 at 10:28
  • thanks! that worked. If you post this as a reply I'll validate it; else if you think this is just the most trivial of questions, I can delete it as well. – PaoloCrosetto Jun 18 '19 at 10:50
  • you're most welcome, I think it's better to delete it. – A. Suliman Jun 18 '19 at 10:56
  • I don't think deleting is good. Seems like a useful question that those inexperienced with NSE, quosures, etc., would find useful. – Curt F. Jun 18 '19 at 23:19
  • Glad you didn't delete! Proved helpful today - thank you all :) – Brent Dec 15 '20 at 00:02

0 Answers0