2

I am trying to make a function that uses summarise_if (or summarise_at) to calculate the correlation between one column and many others in the data set.

data_set <- data.frame(grp = rep(c("a","b","c"), each = 
3), x = rnorm(9), y = rnorm(9), z = rnorm(9))

multiple_cor <- function(d, vars){
 d %>% 
  dplyr::group_by(grp) %>% 
  dplyr::summarise_at(vars, cor, x) %>% 
  return()
}

multiple_cor(data_set, vars = c("y","z") )

This gives the error:

Error in dots_list(...) : object 'x' not found
Called from: dots_list(...)

I'm am fairly sure this is from the cor function not evaluating x within the right environment, but I am not sure how to get around this issue.

c.carp
  • 21
  • 3
  • Related? https://stackoverflow.com/questions/27773881/r-object-not-found-if-defined-within-a-function-when-using-data-table-dplyr – Roman Luštrik Aug 25 '18 at 05:59
  • Possible duplicate of [R object not found if defined within a function when using data.table dplyr](https://stackoverflow.com/questions/27773881/r-object-not-found-if-defined-within-a-function-when-using-data-table-dplyr) – storaged Aug 25 '18 at 06:29

1 Answers1

3

summarise_at has a funs argument so it can handle anonymous functions. I created a function called cors inside your function and pass that one on to summarise_at inside the funs argument to handle the x.

multiple_cor <- function(d, vars){
  cors <- function(x, a = NULL) {
    stats::cor(x, a)
  }
  d %>% 
    dplyr::group_by(grp) %>% 
    dplyr::summarise_at(vars, funs(cors(x, .))) %>% 
    return()
}

multiple_cor(data_set, vars = c("y","z") )

# A tibble: 3 x 3
  grp        y      z
  <fct>  <dbl>  <dbl>
1 a      0.803  0.894
2 b     -0.284 -0.949
3 c      0.805 -0.571

The outcome of the function is exactly identical as the following lines of code:

data_set %>% 
  group_by(grp) %>% 
  summarise(cxy = cor(x, y),
            cxz = cor(x, z))

# A tibble: 3 x 3
  grp      cxy    cxz
  <fct>  <dbl>  <dbl>
1 a      0.803  0.894
2 b     -0.284 -0.949
3 c      0.805 -0.571

Read this dplyr documentation.

And this google groups discussion.

phiver
  • 23,048
  • 14
  • 44
  • 56