r - 在具有更新角色条件的 R 配方中不起作用
问题描述
如果variable_names
包含名称我想更新那些成为 Not_predictors 的角色;而如果variable_names
是 NA 我想在函数中跳过这一步。但是,在添加条件时,我得到了错误。请参阅下面的 repex 代码。
# Example Data
pred1 <- c(4,2,1)
pred2 <- c(4,2,1)
pred3 <- c(4,2,1)
pred4 <- c(4,2,1)
id_nr <- c(1, 2, 3)
y <- c(1,5,2)
data <- tibble::tibble(pred1, pred2, pred3, pred4, id_nr, y)
# Want to remove thes variables from predictor role if variable_names is not NA
variable_names <- c("pred1", "pred2")
# Without condition it works
recipe <- data %>%
recipes::recipe(y ~ .) %>%
recipes::update_role(id_nr, new_role = "id variable") %>%
recipes::update_role(dplyr::all_of(variable_names), new_role = "Not_predictors") %>%
recipes::step_pca(., recipes::all_predictors(), num_comp = 2) %>%
recipes::prep()
recipe
# But when adding the condition I get error.
recipe <- data %>%
recipes::recipe(y ~ .) %>%
recipes::update_role(id_nr, new_role = "id variable") %>%
{
if(!is.na(variable_names[1])){
recipes::update_role(dplyr::all_of(variable_names), new_role = "Not_predictors")
} else {
.
}
} %>%
recipes::step_pca(., recipes::all_predictors(), num_comp = 2) %>%
prep()
recipe
这是错误:
Error: $ operator is invalid for atomic vectors
In addition: Warning message:
No selectors were found
任何帮助深表感谢。
解决方案
我从RStudio 社区收到了一个解决方案:
recipe <- data %>%
recipes::recipe(y ~ .) %>%
recipes::update_role(id_nr, new_role = "id variable") %>%
(function(x){
if(!is.na(variable_names[1])){
x %>% recipes::update_role(dplyr::all_of(variable_names), new_role = "Not_predictors")
} else {
x
}
}) %>%
recipes::step_pca(., recipes::all_predictors(), num_comp = 2) %>%
recipes::prep()
recipe
推荐阅读
- pine-script - 仅回测最后 500 个柱的策略
- javascript - JS Outlook 插件:如何获取所有电子邮件数据,例如主题、正文、附件等
- webpack - Webpack 使文件夹和文件同名
- bash - 删除列表中不存在的目录和子目录
- java - 正则表达式从给定字符串解析百分比范围
- javascript - 如何修复反应钩子中的数组状态过滤数据
- spring-aop - 如何在spring AOP切入点中为args分配多参数
- jquery - Jquery ajax - 无法加载资源:net::ERR_CERT_AUTHORITY_INVALID
- spring - 如何通过千分尺库捕获 REST 端点的指标
- r - 用 mob 预测:R 中基于模型的递归分区