首页 > 解决方案 > 如何将配方中的 update_role(或步骤)函数应用于多个列

问题描述

我正在使用recipes来自tidymodels. 我正在尝试同时update_role为几列。例子:

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")

我收到错误Error: Not all functions are allowed in step function selectors (e.g.c ). See ?selections. Here's documentation for selections
我无法手动输入所有这些。

标签: rr-recipestidymodels

解决方案


这是尝试使用purrr::map. 下面的代码有效,但也许有更好的方法。

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

编辑。

这是另外两个示例,第一个以 R 为基数Map,另一个以purrr::map. 他们都给出了相同的结果。

该列表cols_to_update现在有 2 个成员,"a"并且"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")

推荐阅读