Skip to content

Instantly share code, notes, and snippets.

@andrewmoles2
Last active June 11, 2024 17:21
Show Gist options
  • Save andrewmoles2/ac88ac877131d93067d340b857c8f3af to your computer and use it in GitHub Desktop.
Save andrewmoles2/ac88ac877131d93067d340b857c8f3af to your computer and use it in GitHub Desktop.
# function to make table of descriptive statistics
# rows are column names, columns are the descriptives (mean, min etc.)
descriptive_tab <- function(df, cols, round_digits = 2) {
# cols needs to be a vector
# cols <- c('col1', 'col2', 'col3')
tab <- data.frame(
t(
apply(
df[, cols],
MARGIN = 2,
function (x) c(
mean = round(mean(x, na.rm = TRUE), round_digits),
median = round(median(x, na.rm = TRUE), round_digits),
min = round(min(x, na.rm = TRUE), round_digits),
max = round(max(x, na.rm = TRUE), round_digits),
standard_deviation = round(sd(x, na.rm = TRUE), round_digits)
)
)
)
)
return(tab)
}
# example use with Iris dataset
iris_cols <- c("Sepal.Length", "Sepal.Width",
"Petal.Length", "Petal.Width")
iris_stats <- descriptive_tab(
df = iris,
cols = iris_cols,
round_digits = 3
)
iris_stats
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment