Custom cleaning a vector of strings using janitor::make_clean_names()

Viewed 350

I have a vector that contains column names of a data frame. I want to clean up those strings.

vec_of_names <- c("FIRST_column", 
                  "another-column", 
                  "ALLCAPS-column", 
                  "cOLumn-with___specialsuffix", 
                  "blah#4-column",
                  "ANOTHER_EXAMPLE___specialsuffix",
                  "THIS_IS-Misleading_specialsuffix")

I specifically want to use janitor::make_clean_names() for this cleanup.

janitor::make_clean_names(vec_of_names)

[1] "first_column"                     "another_column"                  
[3] "allcaps_column"                   "c_o_lumn_with_specialsuffix"     
[5] "blah_number_4_column"             "another_example_specialsuffix"   
[7] "this_is_misleading_specialsuffix"

However, I want to apply the following rule:

  1. When the string ends with ___specialsuffix (i.e., 3 underscores and "specialsuffix"),

    • clean with janitor::make_clean_names() only the part BEFORE ___specialsuffix
      (meaning, the value returned from strsplit(x, "___specialsuffix")).

    • then keep the cleaned string pasted back to ___specialsuffix.

  2. Otherwise, if the string doesn't end with ___specialsuffix, then clean it regularly using janitor::make_clean_names() over the entire string.

Desired output will therefore be:

[1] "first_column"                     "another_column"                  
[3] "allcaps_column"                   "c_o_lumn_with___specialsuffix"     ## elements [4] and [6]
[5] "blah_number_4_column"             "another_example___specialsuffix"   ## were handled according to rule #1
[7] "this_is_misleading_specialsuffix"                                     ## outlined above

Thanks a lot for any idea!

1 Answers
vec_of_names <- c("FIRST_column", 
                  "another-column", 
                  "ALLCAPS-column", 
                  "cOLumn-with___specialsuffix", 
                  "blah#4-column",
                  "ANOTHER_EXAMPLE___specialsuffix",
                  "THIS_IS-Misleading_specialsuffix")


library(tidyverse)

suffix <- vec_of_names %>% str_extract(pattern = "___specialsuffix$") %>% replace_na("")
cleaned_without_suffix <- vec_of_names %>% str_remove("___specialsuffix$") %>% janitor::make_clean_names()


output <- paste0(cleaned_without_suffix, suffix)
Related