Created
March 22, 2018 21:15
-
-
Save ateucher/385c87504f3e1f922deb282f03890bd5 to your computer and use it in GitHub Desktop.
Convert between snake_case and camelCase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
camel_to_snake <- function(x, case = c("lower", "upper")) { | |
case <- match.arg(case) | |
case_fun <- switch(case, lower = tolower, upper = toupper) | |
case_fun(gsub("([a-z0-9])([A-Z]+)", "\\1_\\2", x)) | |
} | |
snakeToCamel <- function(x) { | |
x <- tolower(x) | |
gsub("([a-z0-9]+)_([a-z0-9])", "\\1\\U\\2\\E", x, perl = TRUE) | |
} | |
testcamel <- c("camelCaseName", "camel1Case2Name") | |
camel_to_snake(testcamel) | |
#> [1] "camel_case_name" "camel1_case2_name" | |
camel_to_snake(testcamel, case = "upper") | |
#> [1] "CAMEL_CASE_NAME" "CAMEL1_CASE2_NAME" | |
testsnake <- c("snake_case_name", "SNAKE_CASE_NAME", "snake1_case2_name3") | |
snakeToCamel(testsnake) | |
#> [1] "snakeCaseName" "snakeCaseName" "snake1Case2Name3" | |
#' Created on 2018-03-22 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment