Skip to content

Instantly share code, notes, and snippets.

@jmbarbone
Created February 14, 2024 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmbarbone/c4bcaf49eac03fe7dd406b946a1fe77b to your computer and use it in GitHub Desktop.
Save jmbarbone/c4bcaf49eac03fe7dd406b946a1fe77b to your computer and use it in GitHub Desktop.
R SQL snakecase implementation
# 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