select and rename with dplyr and nse

nse

#1

I have data that looks something like this:

test.df <- data.frame(V1 = rnorm(5), test2 = rnorm(5), somethingelse3 = rnorm(5))

I want to:

  • select V1, test2, and rename test2
  • use nse to select test2 and rename it based on two strings str1 and str2

This is the code that I wrote:

str1 <- 'test'
str2 <- 'something'

test.df %>% 
  select(V1,
         !!glue::glue('post_{str1 }') := 
           !!!rlang::sym(glue::glue('{str1}2')))

Alas, the code is selecting the two variables that I want but it is not renaming test2 to post_test as I was intending. What am I doing wrong?


#2

I think you had one too many !s in there (for future reference, it's easier to reproduce if you run your code through reprex, as I have in the example at the bottom). With the code as you had it before, I got the warning

Warning message:
Unquoting language objects with `!!!` is soft-deprecated as of rlang 0.3.0.
Please use `!!` instead.

  # Bad:
  dplyr::select(data, !!!enquo(x))

  # Good:
  dplyr::select(data, !!enquo(x))    # Unquote single quosure
  dplyr::select(data, !!!enquos(x))  # Splice list of quosures

So, as suggested, I modified the !!! to !!:

suppressPackageStartupMessages(library(tidyverse))
test.df <- data.frame(V1 = rnorm(5), test2 = rnorm(5), somethingelse3 = rnorm(5))

str1 <- 'test'
str2 <- 'something'

test.df %>% 
  select(V1,
         !!glue::glue('post_{str1 }') := 
           !!rlang::sym(glue::glue('{str1}2')))
#>            V1  post_test
#> 1  1.60161906  0.3478237
#> 2 -0.04423129 -0.4359105
#> 3  0.22677650  0.4410487
#> 4  0.45244758 -0.7553246
#> 5 -2.19567192 -1.4972165

Created on 2019-01-10 by the reprex package (v0.2.1.9000)


closed #4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.