Использование альтернативного решения - tidyverse.Это ваш набор данных:
mydf <- structure(list(gender = c("M", "F", "M", "F", "F", "other", "M","other"),
race = c(1L, 1L, 2L, 5L, 1L, 4L, 3L, 4L), b1 = c(0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L),
b2 = c(1L, 1L, 0L, 1L, 0L, 0L, 1L, 1L), b3 = c(1L, 0L, 1L, 0L, 1L, 1L, 0L, 0L),
b4 = c(1L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), b5 = c(1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L),
score = c(58L, 63L, 49L, 54L, 55L, 71L, 53L, 68L)),
class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8"))
Затем вы можете создать переменную 'new', используя функции mutate и rowSums
mydf %>%
mutate(new = rowSums(.[starts_with("b",vars = names(.))],na.rm = TRUE))
gender race b1 b2 b3 b4 b5 score new
1 M 1 0 1 1 1 1 58 4
2 F 1 0 1 0 0 1 63 2
3 M 2 1 0 1 0 0 49 2
4 F 5 0 1 0 0 0 54 1
5 F 1 0 0 1 0 1 55 2
6 other 4 0 0 1 0 0 71 1
7 M 3 1 1 0 1 1 53 4
8 other 4 0 1 0 1 0 68 2