Recipe with condition to update roles does not work

If variable_names contains names I want to update the role of those to become Not_predictors; whereas if variable_names is NA I want to skip this step within a function. However, when adding the condition I get and error. Please see repex code below.

# 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

This is the error:

Error: $ operator is invalid for atomic vectors
In addition: Warning message:
No selectors were found 

Any help is much appreciated.


# But when adding the condition I get error. 
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
1 Like