r - 如何将配方中的 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。
我无法手动输入所有这些。
解决方案
这是尝试使用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")
推荐阅读
- powershell - 如何修复“小数”
- pyspark - 将 PySpark ML Word2Vec 模型转换为 Gensim Word2Vec 模型
- java - 我是否正确地将这个伪代码翻译成 Java?
- firefox - SVG 线条在缩小时消失
- mongodb - MongoDB 对数据文件设置最大大小限制
- visual-studio-code - 对象键中的jsdoc连字符
- ios - 在 AVCapturesession 之上添加视图
- python - 无法 pip 安装 tensorflow(不再)
- python - 使用 pd.groupby.sum() 返回的对象制作条形图
- php - PHP SHA 256 没有产生预期的输出