2

I am confused about dplyr functions' arguments and not quite clear about standard evalution (SE) or non-standard evaluation (NSE). I just want to pass a variable to dplyr::arrange() but it failed. However, passing to dplyr::select() works.

> library(dplyr)
> library(magrittr)
> var_name <- "mpg"
> mtcars %>% as_tibble() %>% dplyr::select(var_name)
# A tibble: 32 x 1
 mpg
 * <dbl>
 1  21.0
 2  21.0
 3  22.8
 4  21.4
 5  18.7
 6  18.1
 7  14.3
 8  24.4
 9  22.8
10  19.2
# ... with 22 more rows
> mtcars %>% as_tibble() %>% dplyr::arrange(var_name)
Error in arrange_impl(.data, dots) : 
  incorrect size (1) at position 1, expecting : 32

I searched a solution using SE version and it works:

> mtcars %>% as_tibble() %>% dplyr::arrange_(var_name)

Why dplyr::select() differs from dplyr::arrange() in NSE?

How to fix the error below in global environment?

> as_tibble(mtcars) %>% dplyr::mutate(paste0(var_name,"_Minus1") = mtcars$mpg - 1)
Error: unexpected '=' in "as_tibble(mtcars) %>% dplyr::mutate(paste0(var_name,"_Minus1") ="

Thanks!

Jackman Li
  • 65
  • 1
  • 8
  • Really good article by Wickham http://adv-r.had.co.nz/Computing-on-the-language.html – Aleh Mar 01 '18 at 08:16
  • I "think" `select` was built slightly differently to allow things like selection of column ranges, dropping columns using -column, and multiple columns. The arrange behaviour for a single column is the "norm" but `arrange_at` is again built for multiple column selection and hence the different behaviour. – Stephen Henderson Mar 01 '18 at 08:55
  • Maybe we can't figure out deeper differences unless we analyse the source codes. @Aleh 's recommendation does help and the book has a newer edition now https://adv-r.hadley.nz/ – Jackman Li Mar 04 '18 at 07:44

1 Answers1

1

We can use arrange_at which takes objects

mtcars %>%
   as_tibble() %>%
   dplyr::arrange_at(var_name)

Or another option is to convert to symbol with sym from rlang and evaluate with !!

mtcars %>%
   as_tibble() %>%
   dplyr::arrange(!! rlang::sym(var_name))
akrun
  • 874,273
  • 37
  • 540
  • 662