Skip to content

Instantly share code, notes, and snippets.

@hauselin
Created July 15, 2022 18:04
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 hauselin/adc6a3cbe1fa70f76975407d27fe0a37 to your computer and use it in GitHub Desktop.
Save hauselin/adc6a3cbe1fa70f76975407d27fe0a37 to your computer and use it in GitHub Desktop.
misc helper functions
library(dplyr)
library(broom)
library(modelsummary)
clean_colnames <- function(df) {
new <- tolower(gsub(" ", "_", names(df)))
new <- gsub(".", "_", new, fixed = TRUE)
new <- gsub("(", "", new, fixed = TRUE)
new <- gsub(")", "", new, fixed = TRUE)
names(df) <- new
return(df)
}
ds <- function(data, output = "markdown") {
message(paste(nrow(data), "obs", ncol(data), "cols"))
return(datasummary(All(data) ~ NUnique + PercentMissing + Mean + SD + Min + Median + Max + Histogram, data = data, output = output))
}
tidy <- function(...) {
return(data.table(broom::tidy(...)))
}
scale_minmax <- function(x, new_range = c(0, 1)) {
scale_01 <- (x - min(x, na.rm = T)) / (max(x, na.rm = T) - min(x, na.rm = T))
x_scaled <- scale_01 * (new_range[2] - new_range[1]) + new_range[1]
return(x_scaled)
}
rounddf <- function(data, digits = 3) {
mutate(data, across(where(is.numeric), round, digits = digits))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment