在 dplyr::mutate 中对字符向量中列出的多个变量求和

Sum multiple variables listed in character vector, in dplyr::mutate

我怎样才能让这样的东西工作?我想要 all = sum(onecycle, twocycle),而不必全部输入。

library('dplyr')
library('english')
ex <- data.frame(onecycle = 1:10, twocycle = sample(1:10), recycle = sample(1:10), gvar = rep(1:5, each = 2))

ex %>% 
  mutate(all = sum(paste0(english(1:2), 'cycle'))

这个怎么样:

ex$all=ex %>% select(ends_with("cycle"))%>% rowSums()

您可以使用 dplyr::rowwisebase::rowSums():

ex %>% 
  rowwise %>%
  mutate(cycle_sum=sum(onecycle,twocycle))

ex %>% 
  mutate(cycle_sum = rowSums(.[paste0(english(1:2), 'cycle')]))

这里有一个选项reduce

libary(tidyverse)
ex %>% 
  select(matches('cycle')) %>% 
  reduce(`+`) %>% 
  mutate(ex, all = .)

或者另一种选择是 nest 然后在 mutate

中使用 map/reduce
ex %>% 
   nest(-gvar) %>%
   mutate(all = map(data, ~ .x %>% 
                  reduce(`+`))) %>%
   unnest

以下是我使用 rlang::syms

找到的一些方法
ex %>% 
  rowwise %>% 
  mutate(all = sum(!!!syms(paste0(english(1:2), 'cycle'))))

ex %>% 
  mutate(all = list(!!!syms(paste0(english(1:2), 'cycle'))) %>% reduce (`+`))
library('purrr')

ex %>% 
  mutate(total = pmap_dbl(select(., onecycle, twocycle), sum))

   onecycle twocycle recycle gvar total
1         1        7       8    1     8
2         2        9       9    1    11
3         3        4       6    2     7
4         4        2       7    2     6
5         5        3      10    3     8
6         6        8       3    3    14
7         7        1       2    4     8
8         8       10       1    4    18
9         9        6       5    5    15
10       10        5       4    5    15