This function attempts to convert variables to snake_case, even if it's already in snake_case. The important regex lines were posted by Stack Overflow user epost in "Elegant Python function to convert CamelCase to snake_case?".

snake_case(x)

Arguments

x

A vector of names to convert.

Value

A vector of converted names.

Note

This series of regexes has an advantages over the current implementations of lettercase::str_snake_case() and snakecase::to_snake_case(). The former converts "PatientDOB" to "patientdob" and the latter converts "patient.dob" to "patient_._dob". I'll keep an eye on these packages (i.e., lettercase #1 for 'camelCase' and snakecase #101). I'd prefer to use one of them, instead of maintaining the functions.

Author

Will Beasley

Examples

snake_case(colnames(datasets::OrchardSprays))
#> [1] "decrease"  "rowpos"    "colpos"    "treatment"
snake_case(colnames(datasets::iris))
#> [1] "sepal_length" "sepal_width"  "petal_length" "petal_width"  "species"     
snake_case(c("PatientID", "PatientDOB", "DOB", "name.last", "name.first"))
#> [1] "patient_id"  "patient_dob" "dob"         "name_last"   "name_first"