Search code examples
rfunctiondplyrmutate

R tidyverse: function(df, colName) to apply some dplyr::mutate transformation to given col


# 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...

Solution

  • 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