Using loops with mutate in R to sum columns with partially matching column names

Viewed 132
df <- data.frame(x_1_jr=c(1,2,3,4), x_2_jr=c(1,2,3,4), y_1_jr=c(4,3,2,1), y_2_jr=c(4,3,2,1)

  x_1_jr x_2_jr y_1_jr y_2_jr
1      1      1      4      4
2      2      2      3      3
3      3      3      2      2
4      4      4      1      1

I am trying to generate new variables that are the sum of x and y with the same column name suffix, i.e.

df <- df %>% mutate(z_1_jr= x_1_jr + y_1_jr)

  x_1_jr x_2_jr y_1_jr y_2_jr z_1_jr
1      1      1      4      4      5
2      2      2      3      3      5
3      3      3      2      2      5
4      4      4      1      1      5

I could write this out for each variable combination, but I have a large number of variables(>50 for each x and y group), and would like to use a loop... however, I'm relatively new to R and am not sure where to begin!

Can someone help? Thank you!

EDIT: for additional clarity, the dataset contains other non-numeric variables. There are >700 columns (from a large survey). x_1_jr represents, for example, the number of male individuals ages 1 year, y_1_jr female individuals of 1 year. I am trying to get a total (male plus female of 1 year) for each age group.

A

2 Answers

One dplyr and purrr option could be:

df %>%
 bind_cols(map_dfc(.x = unique(sub(".*?_", "_", names(df))),
                   ~ df %>%
                    transmute(!!paste0("z", .x) := rowSums(select(., ends_with(.x))))))

  x_1_jr x_2_jr y_1_jr y_2_jr z_1_jr z_2_jr
1      1      1      4      4      5      5
2      2      2      3      3      5      5
3      3      3      2      2      5      5
4      4      4      1      1      5      5

An option with base R

df[c("z_1_jr", "z_2_jr")] <- sapply(split.default(df, 
      sub("^[a-z]+_", "", names(df))), rowSums)
df
#  x_1_jr x_2_jr y_1_jr y_2_jr z_1_jr z_2_jr
#1      1      1      4      4      5      5
#2      2      2      3      3      5      5
#3      3      3      2      2      5      5
#4      4      4      1      1      5      5
Related