transform count table into disaggregated table of observations

Viewed 138

I have data in the form of a count table of successes and trials, but for modeling I need these data in a disaggregated trial-level table.

How do I get from this:

dplyr::tibble(
    user_id = c(1,2),
    success = c(3,4),
    trials = c(9, 10)
)

To this:

dplyr::tibble(
    user_id = c(rep(1, 9), rep(2, 10)),
    success = c(rep(1, 3),rep(0, 6), rep(1, 4), rep(0, 6))
)
1 Answers

We can uncount based on the 'trials', then grouped by 'user_id', change the 'success' to binary by creating a logical condition with row_number

library(dplyr)
library(tidyr)
df1 %>%
    uncount(trials) %>%
    group_by(user_id) %>%
    mutate(success =  +(row_number() <= first(success))) %>%
    ungroup
# A tibble: 19 x 2
#   user_id success
#     <dbl>   <int>
# 1       1       1
# 2       1       1
# 3       1       1
# 4       1       0
# 5       1       0
# 6       1       0
# 7       1       0
# 8       1       0
# 9       1       0
#10       2       1
#11       2       1
#12       2       1
#13       2       1
#14       2       0
#15       2       0
#16       2       0
#17       2       0
#18       2       0
#19       2       0

Or with base R using Map and stack

stack(setNames(Map(function(x, y) rep(1:0, c(x, y)), 
     df1$success, df1$trials - df1$success), df1$user_id))[2:1]
Related