2

I´m working with functions and dplyr. Codes are based on this post. I would like to pass some variables to the select argument of dplyr and then perform some analyses. When I use , (coma) to separate the list of the variables that I want to select, R fails to print me the results

library(tidyverse)
df = data.frame(x1 = rnorm(100),
                x2 = rnorm(100),
                x3 = rnorm(100),
                x4 = rnorm(100),
                x5 = rnorm(100))
table <- function(items) {
  items <- enquo(items)
  
  pretty <- df %>% 
    select(!!items) %>% 
    summarise_all(mean)
  
  return(pretty)
}

#x1 only!
table(items = x1)
#>           x1
#> 1 0.08593813


#From x1 until X3
table(items = x1:x3)
#>           x1         x2         x3
#> 1 0.08593813 -0.1965462 0.02651688


#From x1 until X2 AND from X4 untill X5 (the real df is different.)
table(items = x1:x2, x4:x5)
#> Error in table(items = x1:x2, x4:x5): unused argument (x4:x5)
Created on 2022-01-13 by the reprex package (v2.0.1)
Luis
  • 1,388
  • 10
  • 30

1 Answers1

2

It may be better to use enquos with !!!. For the last case, concatenate (c)

  table <- function(items) {
     items <- enquos(items)
  
     pretty <- df %>% 
       select(!!!items) %>% 
       summarise_all(mean)
  
     return(pretty)
   }

-testing

> table(items = x1)
          x1
1 -0.2262251
> table(items = x1:x3)
          x1         x2         x3
1 -0.2262251 0.07106254 0.07618617
> table(items = c(x1:x2, x4:x5))
          x1         x2        x4          x5
1 -0.2262251 0.07106254 0.1151052 -0.06535946

NOTE: table is a base R function. So, it is better to rename the custom function. In addition, the suffix _all, _at, _each are all deprecated in favor of across i.e. summarise(across(everything(), mean))

akrun
  • 874,273
  • 37
  • 540
  • 662