jzadra
jzadra

Reputation: 4284

Rlang: how to treat strings as symbols

Once again I'm baffled by the documentation of rlang and the error messages. I've tried 20 different iterations of this using double and triple bangs, :=, quo, enquo, ensym, and every other unclearly named rlang function.

IF you sense frustration it's because every single time I try to use rlang to deal with variables for object names I run into the same wall. Am I missing something critical? Am I stupid? Is the rlang function names and documentation just really poor?

I'm trying to determine the class of a variable in a tibble. In addition to help with doing this, I would be grateful if someone could suggestion how I would have found the answer to this in the documentation.

require(tidyverse)
require(rlang)

x <- enframe(names(mtcars), name = NULL, value = "var") %>% 
  add_column(df = "mtcars")

x %>% mutate(cls = class(sym(paste0(df, "$", var))))
#> Only strings can be converted to symbols

Created on 2019-10-27 by the reprex package (v0.3.0)

Upvotes: 5

Views: 1581

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269346

1) Parse and evaluate it.

library(dplyr)
library(rlang)

x %>% rowwise %>% mutate(cls = class(eval_tidy(parse_expr(paste0(df, "$", var)))))

2) or use sym from rlang and pull from purrr

library(dplyr)
library(purrr)
library(rlang)

x %>% rowwise %>% mutate(cls = class(pull(eval_tidy(sym(df)), var)))

3) or base R function get to retrieve df:

library(dplyr)

x %>% rowwise %>% mutate(cls = class(get(df)[[var]]))

Upvotes: 4

Related Questions