2

名前が含まれている場合variable_names、それらの役割を Not_predictors になるように更新します。一方、variable_namesNA の場合は、関数内でこのステップをスキップしたいと思います。ただし、条件を追加すると、エラーが発生します。以下の reex コードを参照してください。

# 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 

どんな助けでも大歓迎です。

4

1 に答える 1