Home > Software design >  R: turn string into variable names in `tidytable::complete()`
R: turn string into variable names in `tidytable::complete()`

Time:03-22

I have a tidytable that I would like to run complete on for a given set of columns, but for some reason that I can't figure out, usual methods that turn strings into variable names do not work:

input <- tidytable::tidytable(a = sample(LETTERS, size = 100, replace = TRUE), 
                             b = sample(letters, size = 100, replace = TRUE), 
                             c = runif(n = 100))

expected <- input %>% tidytable::complete.(a, b)

columns <- c("a", "b")

attempt1 <- input %>% tidytable::complete.(!!columns) # Error in get_bys(x, y, by) : by.y columns not in y
attempt2 <- input %>% tidytable::complete.(!!!columns) # Error in get_bys(x, y, by) : by.y columns not in y
attempt3 <- input %>% tidytable::complete.(eval(as.name(columns)))  # Error in get_bys(x, y, by) : by.y columns not in y
attempt4 <- input %>% tidytable::complete.(eval(quote(columns))) # Error in get_bys(x, y, by) : by.y columns not in y

attempt5 <- input %>% tidytable::complete.(as.name(columns)) # Error in CJ(`as.name(columns)` = .Primitive("quote")(a), unique = TRUE,  : 'sorted' is TRUE but element 1 is non-atomic, which can't be sorted; try setting sorted = FALSE
attempt6 <- input %>% tidytable::complete.(vars(tidytable::any_of("a"))) # Error in CJ(`vars(tidytable::any_of(a))` = list(~tidytable::any_of(a)), : 'sorted' is TRUE but element 1 is non-atomic, which can't be sorted; try setting sorted = FALSE

attempt7 <- input %>% tidytable::complete.(as.name(columns, sorted = FALSE)) # Error in as.name(columns, sorted = FALSE) : unused argument (sorted = FALSE)
attempt8 <- input %>% tidytable::complete.(vars(tidytable::any_of("a", sorted = FALSE), sorted = FALSE)) # Error in CJ(`vars(tidytable::any_of(a))` = list(~tidytable::any_of(a)), : 'sorted' is TRUE but element 1 is non-atomic, which can't be sorted; try setting sorted = FALSE

CodePudding user response:

We need syms to convert to symbol and then evaluate (!!!)

input %>% 
   tidytable::complete.(!!! rlang::syms(columns))

-output

# A tidytable: 657 × 3
   a     b         c
   <chr> <chr> <dbl>
 1 A     a        NA
 2 A     b        NA
 3 A     c        NA
 4 A     d        NA
 5 A     e        NA
 6 A     f        NA
 7 A     g        NA
 8 A     h        NA
 9 A     i        NA
10 A     j        NA
# … with 647 more rows
  • Related