I have reviewed many posts on SO (including Using pivot_longer with multiple paired columns in the wide dataset), but have not found a solution to what I need to do.
having initial dataset:
df <- tribble(
~person, ~initial_event_date , ~type_initial, ~visit_prior, ~day_cnt_prior, ~prior_visit_type, ~visit_after, ~day_cnt_after, ~visit_after_type,
'a' , '01-01-2020', 'repair' ,'N', '', '', 'Y','15', 'follow-up',
'b' , '01-17-2020', 'routine' ,'Y', '-4', 'repair', 'N','', '',
'c' , '02-11-2020', 'consult' ,'Y', '-2', 'routine', 'Y','22', 'follow-up',
'd' , '04-01-2020', 'repair' ,'N', '', '', 'Y','12', 'correction'
)
I would like to output a dataframe similar to below because I intend to visualize the data on a time based plot using the timevis
package.
output <- tribble(
~person, ~event_date, ~instance, ~type, ~day_cnt,
'a', '01-01-2020', 'initial' ,'repair' ,'0',
'a', '' , 'visit_after', 'follow-up' , '15',
'b', '01-17-2020', 'initial' , 'routine' ,'0',
'b', '' , 'visit_prior','repair' ,'-4',
'c', '02-11-2020', 'initial' , 'consult' ,'0',
'c', '' , 'visit_prior', 'routine' , '-2',
'c', '' , 'visit_after', 'follow-up' ,'22',
'd', '04-01-2020', 'initial' ,'repair' ,'0',
'd', '' , 'visit_after', 'correction','12'
)
I have tried multiple variations of pivot_longer
such as :
df %>% pivot_longer(
cols = c(type_initial,prior_visit_type, visit_after_type),
names_to = 'instance',
values_to = 'day_cnt'
)
Any suggestions or other SO posts that may point me to the solution I am looking for?