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:
- is there already a function like
conditional_mutate
? If not, this could be handy. Also with the filter. - 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 thedata
argument all the time?