View source: R/get_correlation.R
| get_correlation | R Documentation |
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.
get_correlation(data, formula, na.rm = FALSE, wide = FALSE, quiet = FALSE, ...)
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. |
na.rm |
a logical value indicating whether NA values should be stripped before the computation proceeds. |
wide |
if |
quiet |
if |
... |
further arguments passed to |
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.
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.
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)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.