tidy eval glue custom names w/ dplyr::select

Hi! I was following Tidy eval now supports glue strings to create custom names in data set, and it is awesome!

I got to a bit of a stumbling block when I then wanted to use dplyr::select to grab the variable with the custom name. Is there a way to do this? One work-around would be to select by variable position (i.e., 1, 2, etc), but I was hoping to be more explicit with the newly created name.

I think dplyr::select allows you to pass through both quoted and unquoted variable names, which I am guessing is part of the problem here, right? (But also a great solution for other issues!)

I am using rlang 0.4.1 and dplyr 1.0.2.

library(tidyverse)
library(rlang)
#> 
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#> 
#>     %@%, as_function, flatten, flatten_chr, flatten_dbl, flatten_int,
#>     flatten_lgl, flatten_raw, invoke, list_along, modify, prepend,
#>     splice

suffix <- "A"

dat <- tibble(x = 1:5) %>% 
  mutate(
    "x_{suffix}" := x
  )

dat 
#> # A tibble: 5 x 2
#>       x   x_A
#>   <int> <int>
#> 1     1     1
#> 2     2     2
#> 3     3     3
#> 4     4     4
#> 5     5     5

# doesn't work ----
# are there ways to do this? ----
dat %>% dplyr::select("x_{suffix}")
#> Error: Can't subset columns that don't exist.
#> x Column `x_{suffix}` doesn't exist.

Created on 2021-02-03 by the reprex package (v1.0.0)

Hi,

Here is a way to do this:

library(dplyr)
library(rlang)
library(glue)

suffix <- "A"

dat <- tibble(x = 1:5) %>% 
  mutate(
    "x_{suffix}" := x
  )

dat 
#> # A tibble: 5 x 2
#>       x   x_A
#>   <int> <int>
#> 1     1     1
#> 2     2     2
#> 3     3     3
#> 4     4     4
#> 5     5     5

dat %>% dplyr::select(glue("x_{suffix}"))
#> # A tibble: 5 x 1
#>     x_A
#>   <int>
#> 1     1
#> 2     2
#> 3     3
#> 4     4
#> 5     5

Created on 2021-02-03 by the reprex package (v0.3.0)

You need to wrap the string in the glue function in order for this to work in select(), because it interprets the strings literally. Notice how in mutate you used the Walrus operator := to denote that the string was special, but there is no such thing in select, so you must explicitly wrap it in glue().

Hope this helps,
PJ

3 Likes

Ah, yes, of course! Thank you!!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.