I would like to mutate (in this case transmute) new columns that add all columns which contain a certain pattern. The new columns should also be called the pattern. I would like to avoid pivoting the data into long format and avoid referring to strings attached to the pattern.
In the example below, 'b\\d+' is the pattern:
df <- tribble(
~a1_b1, ~a1_b2, ~a1_b3, ~a2_b1, ~a2_b2, ~a2_b3, ~a3_b1, ~a3_b2, ~a3_b3, ~a4_b1, ~a4_b2, ~a4_b3,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
)
Expected output:
df %>%
transmute(b1 = a1_b1 + a2_b1 + a3_b1 + a4_b1,
b2 = a1_b2 + a2_b2 + a3_b2 + a4_b2,
b3 = a1_b3 + a2_b3 + a3_b3 + a4_b3)
# A tibble: 1 x 3
b1 b2 b3
<dbl> <dbl> <dbl>
1 22 26 30