Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Last active October 16, 2023 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/7752de578526ca53d7a1118fc86ab657 to your computer and use it in GitHub Desktop.
Save andrewheiss/7752de578526ca53d7a1118fc86ab657 to your computer and use it in GitHub Desktop.
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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment