library(tidyverse)
library(palmerpenguins)
penguins <- penguins
glimpse(penguins)
## Rows: 344
## Columns: 8
## $ species <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex <fct> male, female, female, NA, female, male, female, male…
## $ year <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
THESE averages don’t make sense…but this is just a silly demo of how you can calc things row averages without separating variables into different dataframes.
Option 1: use rowwise() and then list individual variables using the c() function (useful if the columns you want to average together aren’t next door to each other.
penguins <- penguins %>%
rowwise() %>%
mutate(average_body_year = mean(c(body_mass_g, year)))
Option 2: if you have variables that are all next door, you can use rowwise() and c_across() to specify a range
penguins <- penguins %>%
rowwise() %>%
mutate(average_bill = mean(c_across(bill_length_mm:bill_depth_mm)))
glimpse(penguins)
## Rows: 344
## Columns: 10
## Rowwise:
## $ species <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
## $ island <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgerse…
## $ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, …
## $ bill_depth_mm <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, …
## $ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186…
## $ body_mass_g <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, …
## $ sex <fct> male, female, female, NA, female, male, female, male…
## $ year <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007…
## $ average_body_year <dbl> 2878.5, 2903.5, 2628.5, NA, 2728.5, 2828.5, 2816.0, …
## $ average_bill <dbl> 28.90, 28.45, 29.15, NA, 28.00, 29.95, 28.35, 29.40,…