I have a dataset that roughly looks like this:
person_id mem_was_there_1 mem_was_there_2 mem_was_there_3 new_number_yn_1 new_number_yn_2 new_number_yn_3
<dbl> <dbl> <dbl> <dbl> <lgl> <lgl> <lgl>
1 100 1 2 3 FALSE TRUE FALSE
2 101 4 5 6 TRUE FALSE FALSE
I need to pivot this data into something like this:
# A tibble: 6 x 4
person_id nr mem_was_there new_number_yn
<dbl> <dbl> <dbl> <lgl>
1 100 1 1 FALSE
2 100 2 2 TRUE
3 100 3 3 FALSE
4 101 1 4 TRUE
5 101 2 5 FALSE
6 101 3 6 FALSE
I would like to use a pivot_longer()
from dplyr
option. I tried using this code, but I do not use what to fill in at the ??? to regex to the third _
. Ideally, I would like a separate names_sep
for both 'mem_was_there_xx' and 'new_number_yn_xx'
df1 %>%
pivot_longer(cols = c(matches("^mem_was_there"), matches("^new_number_yn")),
names_to = c('.value', 'nr'),
names_sep = ??? )
df1 <-
tribble(~person_id, ~mem_was_there_1, ~mem_was_there_2, ~mem_was_there_3, ~new_number_yn_1, ~new_number_yn_2, ~new_number_yn_3,
100, 1, 2, 3, F, T, F,
101, 4, 5, 6, T, F, F)