5

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)

ashwin agrawal
  • 1,603
  • 8
  • 16
jzadra
  • 4,012
  • 2
  • 26
  • 46
  • `x %>% mutate(cls = class(eval(parse(text = paste0(df, "$", var)))))`? – Matt Oct 27 '19 at 21:05
  • @Matt doesn't work as expected. mtcars2 <- mtcars %>% mutate(cyl = as.character(cyl)) x <- enframe(names(mtcars), name = NULL, value = "var") %>% add_column(df = "mtcars2") x %>% mutate(cls = class(eval(parse(text = paste0(df, "$", var))))) – jzadra Oct 27 '19 at 21:25
  • 1
    Yes, I forgot the `rowwise`, it should work if you add that in`x %>% rowwise %>% mutate(cls = class(eval(parse(text = paste0(df, "$", var)))))` – Matt Oct 27 '19 at 21:32

1 Answers1

4

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]]))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Note that if you want to stick with tidyverse in (3) you can use `env_get(environment(), df, inherit = TRUE)` in place of `get(df)` – G. Grothendieck Oct 27 '19 at 22:03