Укажите столбцы для применения в аргументе vars
в mutate_at
, затем в каждом столбце l oop над list
с map
и получите mean
library(dplyr)
library(purrr)
df %>%
mutate_at(vars(starts_with('light')),
list(mean = ~ map_dbl(., mean)))
# A tibble: 3 x 7
# x light_93 light_94 light_95 light_93_mean light_94_mean light_95_mean
# <int> <list> <list> <list> <dbl> <dbl> <dbl>
#1 1 <int [3]> <int [3]> <int [3]> 2 4 6
#2 2 <int [3]> <int [3]> <int [3]> 6 10 45
#3 3 <int [3]> <int [3]> <int [3]> 19 19 31
Или с использованием версии devel
с across
и mutate
df %>%
mutate(across(starts_with('light'), ~ map_dbl(., mean), names = "{col}_mean"))
# A tibble: 3 x 7
# x light_93 light_94 light_95 light_93_mean light_94_mean light_95_mean
# <int> <list> <list> <list> <dbl> <dbl> <dbl>
#1 1 <int [3]> <int [3]> <int [3]> 2 4 6
#2 2 <int [3]> <int [3]> <int [3]> 6 10 45
#3 3 <int [3]> <int [3]> <int [3]> 19 19 31
Можно также использовать разные наборы столбцов с различными функциями
df %>%
mutate(across(starts_with('light'), ~ map_dbl(., mean), names = "{col}_mean"),
across(matches('(94|95)$'), ~ map_dbl(., sum), names = "{col}_sum"))
# A tibble: 3 x 9
# x light_93 light_94 light_95 light_93_mean light_94_mean light_95_mean light_94_sum light_95_sum
# <int> <list> <list> <list> <dbl> <dbl> <dbl> <dbl> <dbl>
#1 1 <int [3]> <int [3]> <int [3]> 2 4 6 12 18
#2 2 <int [3]> <int [3]> <int [3]> 6 10 45 30 135
#3 3 <int [3]> <int [3]> <int [3]> 19 19 31 57 93