f_summary: Summarize a Data Frame with Grouping Variables

View source: R/fsummary.R

f_summaryR Documentation

Summarize a Data Frame with Grouping Variables

Description

Computes summary statistics (n, mean, sd, etc.) for a specified numerical columns in a data frame. The dataset can be analyzed as a whole or split by one or more grouping variables.

The function returns a formatted data frame and includes options to export the results directly to an 'Excel' file.

Usage

f_summary(x, ...)

## S3 method for class 'formula'
f_summary(x, data, ...)

## S3 method for class 'data.frame'
f_summary(
  x,
  columns = NULL,
  group_vars = NULL,
  show_name = TRUE,
  show_n = TRUE,
  show_mean = TRUE,
  show_sd = TRUE,
  show_se = TRUE,
  show_ci = FALSE,
  conf_level = 0.95,
  show_min = TRUE,
  show_max = TRUE,
  show_median = TRUE,
  show_Q1 = TRUE,
  show_Q3 = TRUE,
  show_skew = FALSE,
  show_kurtosis = FALSE,
  digits = NULL,
  export_to_excel = FALSE,
  close_generated_files = FALSE,
  open_generated_files = interactive(),
  save_as = NULL,
  save_in_wdir = FALSE,
  check_input = TRUE,
  digits_excel = NULL,
  allow_integer_decimal_mix = FALSE,
  ...
)

Arguments

x

A data.frame or formula (dispatches to the right method).

...

Further arguments forwarded to f_summary.data.frame.

data

A 'data.frame', 'data.table', or 'tibble'.

columns

The numerical column(s) to summarize if no formula is used. Can be entered as a single character string (e.g., "weight") or as a character vector c("weight", "length"). When omitted, defaults to all numeric columns in data (excluding any columns named in group_vars).

group_vars

A character vector specifying the grouping variables in data (e.g., c("species", "fertilizer")) if no formula is used. If NULL, the entire dataset is summarized.

show_name

Logical. Include variable name. Default TRUE.

show_n

Logical. Include count (n). Default TRUE.

show_mean

Logical. Include mean. Default TRUE.

show_sd

Logical. Include standard deviation. Default TRUE.

show_se

Logical. Include standard error. Default TRUE.

show_ci

Logical. Include the lower and upper bounds of a confidence interval for the mean (columns CI_lower and CI_upper). Default FALSE. This interval is most meaningful when the data are approximately normal or n is large; see Details.

conf_level

Numeric. Confidence level for the interval requested by show_ci, given as a proportion between 0 and 1. Default 0.95 (a 95% confidence interval).

show_min

Logical. Include minimum value. Default TRUE.

show_max

Logical. Include maximum value. Default TRUE.

show_median

Logical. Include median. Default TRUE.

show_Q1

Logical. Include first quartile (25th percentile). Default TRUE.

show_Q3

Logical. Include third quartile (75th percentile). Default TRUE.

show_skew

Logical. Include Skewness (measure of asymmetry). Default FALSE.

show_kurtosis

Logical. Include Excess Kurtosis (measure of "tailedness"). Default FALSE.

digits

Integer. Number of decimal places for the R console output. Default is 2. If NULL, no rounding is applied. (Note: This does not affect the raw numbers exported to Excel).

export_to_excel

Logical. If TRUE, exports results to an 'Excel' file. Default FALSE.

close_generated_files

Logical. If TRUE, forces Excel to close before saving (Windows only). Default FALSE.

open_generated_files

Logical. Whether to open the generated output files after creation. Defaults to TRUE in an interactive R session and FALSE otherwise (e.g. in scripts or automated pipelines). Set to TRUE or FALSE to override this behaviour explicitly.

save_as

Character string. Custom path or filename for the Excel export.

  • If full path: Saves to that location.

  • If filename only: Saves to tempdir() (unless save_in_wdir = TRUE).

  • If directory: Saves as "dataname_summary.xlsx" in that directory.

save_in_wdir

Logical. If TRUE, saves to the current working directory. Default FALSE.

check_input

Logical. If TRUE, performs validation checks on inputs. Default TRUE.

digits_excel

Integer. Number of decimal places for the Excel file cells. Default NULL (no rounding). Defining digits_excel, sets export_to_excel = TRUE when excel output is not intended use: digits instead.

allow_integer_decimal_mix

Logical. If TRUE, intergers in columns with a mix of integers and non-integers are displayed without decimals. Default FALSE, meaning if there are one or more numbers with decimals the whole column contains the number of decimals set by digits.

formula

A formula specifying the columns (right hand side) to be summarized by groups (left hand side). More columns or groups can be added using - or + (e.g., col1 + col2 ~ group1 + group2) to do a sequential summary for each column parameter.

Details

The function computes the following statistics:

  • n: number of observations

  • mean: arithmetic mean

  • sd: standard deviation

  • se: standard error (sd / \sqrt{n})

  • CI_lower, CI_upper: lower and upper bounds of the confidence interval for the mean (if requested)

  • min: minimum value

  • max: maximum value

  • median: median value

  • Q1: 25th percentile

  • Q3: 75th percentile

  • skew: Sample skewness (if requested).

  • kurt: Sample excess kurtosis (if requested).

skew stands for Skewness which is a measure of asymmetry of a distribution around its mean. Where skew values near 0 indicate approximate symmetry, while large positive or negative values indicate noticeable asymmetry.

  • > 0: Right-skewed (long or heavier tail to the right).

  • < 0: Left-skewed (long or heavier tail to the left).

kurt stands for Excess Kurtosis: Tells you about the "tails" and the peak.

  • 0: Same tail heaviness as the normal distribution (mesokurtic).

  • > 0: Heavier tails than normal (Leptokurtic) – indicates frequent outliers.

  • < 0: Lighter tails than normal (Platykurtic) – indicates fewer (or less extreme) outliers than a normal distribution.

The confidence interval reported when show_ci = TRUE is a parametric interval for the mean based on the t-distribution, computed as mean \pm t_{(1 - (1 - conf\_level)/2,\, n - 1)} \times se, where n is the number of non-missing observations. This matches the interval reported by t.test. It assumes the data are approximately normally distributed (or that n is large enough for the central limit theorem to apply); for strongly skewed data, indicated for example by a large skew or kurt, the interval may be unreliable. Groups with fewer than two non-missing observations yield NA bounds.

If group_vars are provided, the statistics are calculated for each group combination. When export_to_excel = TRUE, the file is automatically generated.

Value

A list of class f_summary containing the results data frame.

Author(s)

Sander H. van Delden plantmind@proton.me

Examples


# --- Example 1: Basic Usage (data.frame notation) ---
# Summarize "hp" grouped by "cyl"; columns and group_vars can be positional
summary_mtcars <- f_summary(mtcars, columns = "hp", group_vars = "cyl")
summary_mtcars <- f_summary(mtcars, "hp", "cyl")  # shorthand equivalent
print(summary_mtcars)

# --- Example 2: Multiple Columns & Groups with Custom Toggles ---
# Summarize "hp" and "disp", grouped by "cyl" and "gear", hide Q1/Q3
summary_custom <- f_summary(mtcars,
                            columns    = c("hp", "disp"),
                            group_vars = c("cyl", "gear"),
                            show_Q1    = FALSE,
                            show_Q3    = FALSE)
print(summary_custom)

# --- Example 3: Formula Notation ---
# Identical result to Example 2 using formula interface
# and export output to excel
summary_formula <- f_summary(hp + disp ~ cyl + gear,
                             data    = mtcars,
                             show_Q1 = FALSE,
                             show_Q3 = FALSE,
                             export_to_excel = TRUE)
print(summary_formula)

# --- Example 4: Distributional Stats & Digits ---
# Add skewness and kurtosis, control rounding
summary_dist <- f_summary(Sepal.Length + Petal.Length ~ Species,
                          data          = iris,
                          show_skew     = TRUE,
                          show_kurtosis = TRUE,
                          digits        = 3)
print(summary_dist)

# --- Example 5: Custom Print Formatting ---
summary_iris <- f_summary(iris, "Sepal.Length", group_vars = "Species")
print(summary_iris, col_width = 10, table_width = 70)


# --- Example 6: Confidence Interval for the Mean ---
# Add a 95% CI for the mean of Sepal.Length within each Species.
summary_ci <- f_summary(Sepal.Length ~ Species,
                        data    = iris,
                        show_ci = TRUE)
print(summary_ci)

# Use a 90% interval instead
summary_ci90 <- f_summary(Sepal.Length ~ Species,
                          data       = iris,
                          show_ci    = TRUE,
                          conf_level = 0.90)
print(summary_ci90)

rfriend documentation built on July 7, 2026, 1:06 a.m.