Created
February 14, 2024 05:58
-
-
Save jmbarbone/c4bcaf49eac03fe7dd406b946a1fe77b to your computer and use it in GitHub Desktop.
R SQL snakecase implementation
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
# nolint start: object_usage_linter. | |
sql_snakecase0 <- function(.data, new, old = new, na = "(missing)") { | |
force(old) | |
na <- as.character(na) | |
dplyr::mutate( | |
.data, | |
!!rlang::sym(new) := tolower(!!rlang::sym(old)), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), "\\%", "percent "), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), "\\#", "n "), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), " +", "_"), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), "[^a-z0-9]+", "_"), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), "_+", "_"), | |
!!rlang::sym(new) := REGEXP_REPLACE(!!rlang::sym(new), "^_+|_+$", ""), | |
!!rlang::sym(new) := dplyr::if_else(!!rlang::sym(new) == "", na, !!rlang::sym(new)) | |
) | |
} | |
sql_snakecase <- function(.data, new, old = new, na = "(missing)") { | |
force(old) | |
na <- as.character(na) | |
dplyr::mutate( | |
.data, | |
!!rlang::sym(new) := | |
# series of replacements -- otherwise may be a bunch of | |
REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( | |
tolower(!!rlang::sym(old)), | |
"\\%", "percent "), | |
"\\#", "n "), | |
" +", "_"), | |
"[^a-z0-9]+", "_"), | |
"_+", "_"), | |
"^_+|_+$", ""), | |
# replace empty strings | |
!!rlang::sym(new) := dplyr::if_else( | |
!!rlang::sym(new) == "", | |
na, | |
!!rlang::sym(new) | |
) | |
) | |
} | |
# nolint end: object_usage_linter. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment