# 0. Some data frame
df <- tibble::tibble( A = c('12 Z 34', 'N56\t709') )
df
# 1. Desired result (with pipes and mutate())
df %>%
# Removes all of the white space characters
dplyr::mutate(A = gsub("\\s", "", A))
# 2. !!! Define a function so it can applied to some given column name !!!
clean_col <- function(df, colName) {
df <- df %>%
dplyr::mutate(colName = gsub("\\s", "", colName))
return(df)
}
# 3. Apply function to given column (non functional :-( )
clean_col(df, "A")
# 4. Working solution but not as elegant as with %>% and dplyr::mutate
# (as in step 2.)
clean_col_sol <- function(df, colName) {
df[[colName]] <- gsub("\\s", "", df[[colName]])
return(df)
}
clean_col_sol(df, "A")
- Fact: Transforming one given column with dplyr pipes and mutate is fine.
- Goal: I would like to define a function taking a data frame and a column name, and apply some transformation to that column (pipe, mutate), saving the result in the same column name.
- The version with the function does not work as expected...
- I tried a few things, without much success for now: {{}}, !!, UQ, sym, ... to no avail
- A function using df[[colName]] does as expected but is not as elegant as the version with pipes and mutate...