# 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")
Using {{
and passing an unquoted column name you could do:
df <- tibble::tibble( A = c('12 Z 34', 'N56\t709') )
clean_col <- function(df, colName) {
dplyr::mutate(df, {{colName}} := gsub("\\s", "", {{colName}}))
}
clean_col(df, A)
#> # A tibble: 2 × 1
#> A
#> <chr>
#> 1 12Z34
#> 2 N56709
Or passing as a string and using the .data
pronoun:
clean_col <- function(df, colName) {
dplyr::mutate(df, "{colName}" := gsub("\\s", "", .data[[colName]]))
}
clean_col(df, "A")
#> # A tibble: 2 × 1
#> A
#> <chr>
#> 1 12Z34
#> 2 N56709
Created on 2022-09-23 with reprex v2.0.2