Create new columns lopping an array inside mutate (dplyr)

I have the following dummy data frame called df:

A1 A2 A3 B1 B2 B3 C1 C2 C3
1  1  1  2  2  2  3  3  3

and I would like to sum columns that contain the same letter into a new column (naming it using the corresponding letter).

I would expect this result:

A1 A2 A3 B1 B2 B3 C1 C2 C3 A B C
1  1  1  2  2  2  3  3  3  3 6 9

I know I can achieve this result using mutatefrom dyplr:

mutate(df,
       A = A1 + A2 + A3,
       B = B1 + B2 + B3,
       C = C1 + C2 + C3)

Is there any way to do it using a vector like letters <- c("A", "B", "C") and looping over that vector inside the mutate function? Something like:

mutate(df,
       letters = paste0(letters,"1") + paste0(letters,"2") + paste0(letters,"3") )

Upvotes: 2

Views: 136

Answers (1)

tmfmnk
tmfmnk

Reputation: 40161

One dplyr and purrr solution could be:

bind_cols(df, map_dfc(.x = LETTERS[1:3],
                      ~ df %>%
                       transmute(!!.x := rowSums(select(., starts_with(.x))))))

  A1 A2 A3 B1 B2 B3 C1 C2 C3 A B C
1  1  1  1  2  2  2  3  3  3 3 6 9

Upvotes: 1

Related Questions