Last active
June 11, 2024 17:21
-
-
Save andrewmoles2/ac88ac877131d93067d340b857c8f3af to your computer and use it in GitHub Desktop.
This file contains 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
# 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