My goal is to write a pipeable function which applies a (custom) function to a specified column; when the column is missing the original dataframe is returned (without any error/warning). In this example the floor()
function is used as simple example.
library(tidyverse)
floor_if_not_missing <- function(df, col_name){
col_exists <- df %>%
dplyr::select(dplyr::any_of(rlang::as_label(rlang::enquo(col_name)))) %>%
ncol()
if(col_exists== 0){
return(df)
} else {
df %>%
mutate({{col_name}} := floor({{col_name}}))
}
}
mtcars %>% head(5)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
mtcars %>% head(5) %>% floor_if_not_missing(mpg)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18 8 360 175 3.15 3.440 17.02 0 0 3 2
mtcars %>% head(5) %>% floor_if_not_missing(miles_per_gallon)
#> mpg cyl disp hp drat wt qsec vs am gear carb
#> Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#> Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#> Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#> Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#> Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
This solution (and especially the verification part if a column exists) is a bit clumpsy.
Can you suggest any cleaner/tidyer approach?