2

I'm using the recipes package from tidymodels. I'm trying to update_role for a few columns at the same time. Example:

library(recipes)
library(dplyr)

cols_to_update = list()
cols_to_update[["a"]] <- c("mpg", "cyl")

mtcars %>% 
    recipe() %>% 
    update_role(cols_to_update[["a"]], new_role = "new_role")

I get error Error: Not all functions are allowed in step function selectors (e.g.c). See ?selections. Here's documentation for selections.
There's no way I can type all of them by hand.

mihagazvoda
  • 1,057
  • 13
  • 23
  • Try `update_role(mpg, cyl, new_role = "new_role")`. This just lists the variables, no need for `c()`, like the error message says. – Rui Barradas Dec 29 '19 at 16:29
  • It works, thank you! But it's not what exactly I want. I already have a vector of column names saved to a variable. (I updated the code so you can see what I want). Is there a way to use/transform `cols_to_update` so it can be used as an input? – mihagazvoda Dec 29 '19 at 17:33
  • It worked with me: `update_role(cols_to_update, new_role = "new_role")`. I ran this with `cols_to_update <- c("mpg", "cyl")`. – Rui Barradas Dec 29 '19 at 18:11
  • Wow, ok. Works for me too. I wanted to make the example simpler but now it's too simple and it works. The thing is that I have a named list of vectors of variables. (I updated the example again.) – mihagazvoda Dec 30 '19 at 07:44
  • See if my answer below solves the problem. – Rui Barradas Dec 30 '19 at 08:14

1 Answers1

0

Here is an attempt at solving the question's problem using purrr::map. The code below works but maybe there are better ways.

library(recipes)
library(dplyr)

cols_to_update <- list()
cols_to_update[["a"]] <- c("mpg", "cyl")


purrr::map(cols_to_update, function(x){
  mtcars %>%
    recipe() %>%
    update_role(x, new_role = "new_role")
})
#$a
#Data Recipe
#
#Inputs:
#
#     role #variables
# new_role          2
#
#  9 variables with undeclared roles

Edit.

Here are two other examples, the first with base R Map and the other with purrr::map. They both give the same results.

The list cols_to_update now has 2 members, "a" and "b".

cols_to_update[["b"]] <- c("disp", "wt", "carb")

Map(function(x, y){
  mtcars %>%
    recipe() %>%
    update_role(x, new_role = y)
}, cols_to_update, "new_role")

purrr::map(cols_to_update, function(x, y){
  mtcars %>%
    recipe() %>%
    update_role(x, new_role = y)
}, "new_role")
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66