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'))
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')]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With