Conditional mutate

Programming daily with R, I encounter a lot of times the need for a chunk of code like this:

if(condition){
  data <- data %>%
     mutate(...)
}

Now, recently I thought that I could integrate this in a pipeline as follows:

conditional_mutate <- function(data, ..., condition){
  if(condition){
    data %>%
      dplyr::mutate(...)
  }else{
    data
  }
}
data <- data %>%
  conditional_mutate(..., condition = condition)

An example could be

today_I_feel_like_characters <- TRUE
mtcars %>%
  as_tibble() %>%
  conditional_mutate(cyl = as.character(cyl), condition = today_I_feel_like_characters )

I have two questions regarding this:

  1. is there already a function like conditional_mutate? If not, this could be handy. Also with the filter.
  2. my function is probably inefficient because if I understand R correctly, it makes a local copy of data. Can this be programmed more efficiently? I guess dplyr::mutate does not copy the data argument all the time?

You can use case_when() from {dplyr} inside a call to mutate(), which allows you to conditionally mutate columns.

Thank you for your quick response. I know about case_when. This is not what I am looking for though. The condition is unrelated to the .data. I'll add a reprex to be more comprehensible.