unquote a column name given in another column

In dplyr verbs, I understand how to unquote a column name given as a character in the environment:

var <- "height"

starwars %>%
  transmute(test = !!sym(var))
# or
starwars %>%
  transmute(test = .data[[var]])

But what if the column name is given in another column in the same tibble? E.g.:

starwars %>%
  mutate(selected.var = "height") %>%
  transmute(test = !!sym(selected.var))
# Error in is_symbol(x) : object 'selected.var' not found

(Intended output would be the same as the two examples above.) I don't see this use-case covered in the programming vignette, and I'm seeing that the tidyeval book is no longer current. Apologies if I've missed this in the documentation.

Unclear on the question

suppressPackageStartupMessages({
  library(dplyr)
})

var <- "height"

starwars %>%
  transmute(test = !!sym(var))
#> # A tibble: 87 x 1
#>     test
#>    <int>
#>  1   172
#>  2   167
#>  3    96
#>  4   202
#>  5   150
#>  6   178
#>  7   165
#>  8    97
#>  9   183
#> 10   182
#> # … with 77 more rows
# or
starwars %>%
  transmute(test = .data[[var]])
#> # A tibble: 87 x 1
#>     test
#>    <int>
#>  1   172
#>  2   167
#>  3    96
#>  4   202
#>  5   150
#>  6   178
#>  7   165
#>  8    97
#>  9   183
#> 10   182
#> # … with 77 more rows

See the FAQ: How to do a minimal reproducible example reprex for beginners, which is what my post is. The reason for my question is that the reprex does not reproduce the error.

Are you using dplyr_1.0.5?

You're not reproducing the error for the final command? I omitted the output from the first block of code for brevity's sake since there is no error and it is working as intended.
Yes, I'm using 1.0.5.

Apologies. One of the advantages of a reprex is precisely that it will throw the error with one cut-and-paste pass.

This is how'd I'd do it

suppressPackageStartupMessages({
  library(dplyr)
})

var <- "height"

starwars %>%
  mutate(selected.var = !!sym(var)) %>%
  transmute(test = selected.var)
#> # A tibble: 87 x 1
#>     test
#>    <int>
#>  1   172
#>  2   167
#>  3    96
#>  4   202
#>  5   150
#>  6   178
#>  7   165
#>  8    97
#>  9   183
#> 10   182
#> # … with 77 more rows

or

suppressPackageStartupMessages({
  library(dplyr)
})

var <- "height"

starwars %>%
  transmute(test = !!sym(var))
#> # A tibble: 87 x 1
#>     test
#>    <int>
#>  1   172
#>  2   167
#>  3    96
#>  4   202
#>  5   150
#>  6   178
#>  7   165
#>  8    97
#>  9   183
#> 10   182
#> # … with 77 more rows

Thanks. I did use reprex - I just shortened the output afterward.

In my actual use-case, I really need to have selected.var be a column within the tibble, because it can vary. So it cannot be a static variable in the environment.

Glad to take a look at an illustration.

This topic was automatically closed 21 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.