在dplyr :: mutate

时间:2018-03-21 16:31:24

标签: r dplyr symbols 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'))

5 个答案:

答案 0 :(得分:3)

您可以使用base::rowSums()ex %>% rowwise %>% mutate(cycle_sum=sum(onecycle,twocycle))

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

OR

print $(tput bold)"Text is bold"$(tput sgr0)

答案 1 :(得分:2)

以下是reduce

的一个选项
libary(tidyverse)
ex %>% 
  select(matches('cycle')) %>% 
  reduce(`+`) %>% 
  mutate(ex, all = .)

或另一个选项是nest,然后在map/reduce

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

答案 2 :(得分:1)

怎么样:

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

答案 3 :(得分:0)

以下是我使用rlang::syms

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

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

答案 4 :(得分:0)

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