0

I'm building a function that you provide a dataframe and a vector of variable names that are numeric - and i want it to return a dataframe with a corresponding variable for each numeric vector that splits it to intervals.

I know how to do it with one variable, but with multiple var names I get "Error: The LHS of := can't be spliced with !!! ".

Here is a reproducible example:

library(tidyverse)

vars <- c("wt", "qsec")
new_vars <- map_chr(vars, ~ paste0(.x, "_bin"))
bins <- map(vars, ~ quantile(mtcars[,.x], na.rm = T))
result <- mtcars %>% 
  mutate(!!!new_vars := map2(vars, bins, ~ cut(mtcars[,.x], breaks = .y))) 

What I want to get is mtcars but with 2 extra columns. 1. wt_bin - which will be the quantile interval "wt" matches to 2. qsec_bin - which will be the quantile interval "qsec" matches to

I know it has something to do with !!!new_vars := but I can't seem to understand exactly the problem.

Thanks!

guyx1992
  • 13
  • 3
  • Are you trying to create a single column?. `mutate` creates single variable unless it is an expression – akrun Apr 16 '19 at 15:15
  • I'm trying to create multiple columns. In this example i'm trying to create 2 new columns. – guyx1992 Apr 16 '19 at 15:35

2 Answers2

3

You could do it without mutate and dodge the nse too:

map2_dfc(vars, bins, ~ cut(mtcars[, .x], .y, labels = F)) %>% 
  set_names(new_vars) %>% 
  bind_cols(mtcars, .)
Nate
  • 10,361
  • 3
  • 33
  • 40
1

We can use := with transmute

library(tidyverse)
map2_dfc(vars, bins, ~
                 mtcars %>%
                       transmute(!! paste0(.x, "_bin") := 
                           cut(!! rlang::sym(.x), breaks = .y))) %>% 
                 bind_cols(mtcars,.)
akrun
  • 874,273
  • 37
  • 540
  • 662