Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

symbols

r

dplyr

How can I get something like this to work? I want all = sum(onecycle, twocycle), without having to type it all out.

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'))
like image 474
IceCreamToucan Avatar asked Oct 20 '25 05:10

IceCreamToucan


2 Answers

You could use dplyr::rowwise or the base::rowSums():

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

OR

ex %>% 
  mutate(cycle_sum = rowSums(.[paste0(english(1:2), 'cycle')]))
like image 138
nadizan Avatar answered Oct 21 '25 19:10

nadizan


Here is one option with reduce

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

Or another option is to nest and then use map/reduce within mutate

ex %>% 
   nest(-gvar) %>%
   mutate(all = map(data, ~ .x %>% 
                  reduce(`+`))) %>%
   unnest
like image 43
akrun Avatar answered Oct 21 '25 18:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!