Mutate() RHS multiple columns

dplyr

#1

I'm sure there is a simple way to create a new column with mutate aggregating many columns at once. So, for a tibble

library(tidyverse)
tbl <- tibble(a = 1:3, ab = 1:3 * 2, b = letters[1:3]) %T>% print()
#> # A tibble: 3 x 3
#>       a    ab b    
#>   <int> <dbl> <chr>
#> 1     1     2 a    
#> 2     2     4 b    
#> 3     3     6 c

apply something like

tbl %>% mutate(aggr_column = sum(vars(starts_with("a")))

and get aggr_column with values c(3, 6, 9)


#2

You can do something like this:

library(tidyverse)
tbl <- tibble(a = 1:3, ab = 1:3 * 2, b = letters[1:3]) 


tbl %>% 
  mutate(aggr_column = rowSums(select(., starts_with("a"))))
#> # A tibble: 3 x 4
#>       a    ab b     aggr_column
#>   <int> <dbl> <chr>       <dbl>
#> 1     1     2 a               3
#> 2     2     4 b               6
#> 3     3     6 c               9

Created on 2018-09-13 by the reprex package (v0.2.0).


#3

I've found my own code that I wrote a week ago :slight_smile:

library(tidyverse)
tibble(a = 1:3, ab = 1:3 * 2, b = letters[1:3]) %>% 
    mutate(agg = pmap_dbl(select(., starts_with("a")), sum))
#> # A tibble: 3 x 4
#>       a    ab b       agg
#>   <int> <dbl> <chr> <dbl>
#> 1     1     2 a         3
#> 2     2     4 b         6
#> 3     3     6 c         9

#4

pmap_dbl is indeed how I would do/did it "in general", but from your questions I got a vibe that you value "code golf" a bit more, so decided to make it as concise as possible :slight_smile: