library(tidyverse)
withr::with_seed(1234, {
Wave1_original <- tibble(
AID = sample(1:51, 1000, replace = TRUE),
H1NM12A = sample(0:1, 1000, replace = TRUE),
H1NM12B = sample(0:1, 1000, replace = TRUE),
H1NM12C = sample(0:1, 1000, replace = TRUE),
H1NM12D = sample(0:1, 1000, replace = TRUE),
H1NM12E = sample(0:1, 1000, replace = TRUE),
H1NM12F = sample(0:1, 1000, replace = TRUE),
H1NM12G = sample(0:1, 1000, replace = TRUE),
H1NM12H = sample(0:1, 1000, replace = TRUE),
H1NM12I = sample(0:1, 1000, replace = TRUE),
H1NM12J = sample(0:1, 1000, replace = TRUE)
)
})
Wave_1 <- Wave1_original %>%
# Make all these binary. across() runs the same mutate function across a bunch
# of different columns; the ~ specifies the function and the .x is a
# placeholder for "the current column"
mutate(across(starts_with("H1NM12"), ~ifelse(.x == 1, 1, 0))) %>%
# Group by individual id
group_by(AID) %>%
# Add up all the binary columns within each individual
summarize(activities_mom = sum(across(starts_with("H1NM12"), ~sum(.x))))
Wave_1
#> # A tibble: 51 × 2
#> AID activities_mom
#> <int> <dbl>
#> 1 1 39
#> 2 2 95
#> 3 3 105
#> 4 4 109
#> 5 5 59
#> 6 6 101
#> 7 7 112
#> 8 8 93
#> 9 9 58
#> 10 10 78
#> # ℹ 41 more rows
Created on 2023-10-16 with reprex v2.0.2