Learn R Programming

moderndive (version 0.8.0)

get_correlation: Get correlation value in a tidy way

Description

Determine the Pearson correlation coefficient between an outcome variable on the left-hand side of formula and one or more explanatory variables on the right-hand side, using pipeable and formula-friendly syntax.

Usage

get_correlation(data, formula, na.rm = FALSE, wide = FALSE, quiet = FALSE, ...)

Value

A tibble. For a single right-hand side variable, a 1×1 tibble (or 1 row per group) with column cor. For multiple right-hand side variables: long format (default) with columns predictor and cor

(plus any grouping variables), or wide format (wide = TRUE) with one column per predictor.

Arguments

data

a data frame object

formula

a formula with the outcome variable on the left and one or more explanatory variables on the right (e.g. y ~ x or y ~ x1 + x2 + x3).

na.rm

a logical value indicating whether NA values should be stripped before the computation proceeds.

wide

if TRUE and the formula has more than one right-hand-side variable, pivot the result wider so that each predictor becomes a column. Has no effect on single-predictor formulas. Default FALSE.

quiet

if TRUE, suppress the informational message that points to corrr::correlate() for full pairwise correlation matrices. Default FALSE.

...

further arguments passed to stats::cor()

Details

For a single right-hand side variable, the result is a 1-column tibble (or one row per group if data is grouped) named cor. For multiple right-hand side variables, the result is a long tibble with one row per (predictor, group) combination by default; pass wide = TRUE to pivot it to one column per predictor.

Examples

Run this code
library(moderndive)
library(dplyr)

# Single explanatory variable:
un_member_states_2024 %>%
  get_correlation(formula = life_expectancy_2022 ~ gdp_per_capita, na.rm = TRUE)

# Multiple explanatory variables — long format:
un_member_states_2024 %>%
  get_correlation(
    formula = life_expectancy_2022 ~ gdp_per_capita + fertility_rate_2022 + hdi_2022,
    na.rm   = TRUE,
    quiet   = TRUE
  )

# Multiple explanatory variables — wide format:
un_member_states_2024 %>%
  get_correlation(
    formula = life_expectancy_2022 ~ gdp_per_capita + fertility_rate_2022 + hdi_2022,
    wide    = TRUE,
    na.rm   = TRUE,
    quiet   = TRUE
  )

# Group by one variable:
un_member_states_2024 %>%
  group_by(continent) %>%
  get_correlation(formula = life_expectancy_2022 ~ gdp_per_capita, na.rm = TRUE)

# Group by two variables:
un_member_states_2024 %>%
  group_by(continent, income_group_2024) %>%
  get_correlation(formula = life_expectancy_2022 ~ gdp_per_capita, na.rm = TRUE)

Run the code above in your browser using DataLab