Could a `str_to_snake` function be made to convert strings to snake-case?
It'd be useful to have a str_to_snake function in stringr.
I think the main use for this would be to rename column names to snake-case:
rename_with(data, stringr::str_to_snake)
It would enable not taking on another package dependency with janitor::clean_names in many user's workflows
Hmmmm, we'd probably want to add str_to_camel() (strToCamel()?) for completeness.
str_to_camel would be cool too.
I think strToCamel is a cool name, but str_to_camel is better as it's consistent with with how str_to_upper and str_to_title are named.
I have a student (@librill) who would like to tackle this.
We see that the existing str_to_title() etc are calling stringi::stri_trans_totitle(), which calls a C function in stringi.
So, would the preferred approach be:
- PR a
stri_trans_toCamel()and corresponding C function tostringi, the later PRstringrfor the wrapper. or - PR a
str_to_camel, calling an underlying C function, directly tostringr
I think you could just implement it in R, using a regular expression or other stringr functions.
I'm not a stringr dev so I'm just giving my two cents. I believe that the cost of adding janitor as a dependency is marginal and outweighs the time spent to write rename_with(data, stringr::str_to_snake), especially since janitor mostly depends on packages that are part of the tidyverse.
There's also snakecase (the actual package that janitor relies on to convert strings to particular case types) which is relatively lightweight and only depends on stringr and stringi.
That said, I have an old to_snake_case() function that I wrote for that purpose before I knew janitor/snakecase, in case that's of any use:
to_snake_case <- function(x) {
x <- stringr::str_replace_all(x, c(
r"{[^\p{L}\p{N}]+|(?<=\p{Lu})(?=\p{Lu}\p{Ll})|(?<=\p{Ll})(?=\p{Lu}|\p{N})|(?<=\p{N})(?!\p{N})}" = "_",
"^_|_$" = ""
))
tolower(x)
}
Removing the raw string will make the function slightly faster.
I always thought that using regex for this wasn't ideal but I'm sure Hadley knows better than me.