【问题标题】:In R recipe with condition to update roles does not work在具有更新角色条件的 R 配方中不起作用
【发布时间】:2020-11-19 14:24:17
【问题描述】:

如果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 

非常感谢任何帮助。

【问题讨论】:

  • 我不认为这样的事情会这么好。目前,tidymodels 不支持始终很好地选择 no 变量,但这是我们正在努力解决的问题。您想chime in on this issue 说明您的用例和遇到的问题吗?

标签: r tidymodels r-recipes


【解决方案1】:

我收到了来自RStudio community的解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2015-04-14
    相关资源
    最近更新 更多