df%>%arrange(id,drugclass, start_date, end_date)%>%
group_by(id,drugclass)%>%
if(row_number==1) then {a1=a3; a2=a4}
else if ( ) {a1=a5; a2=a6}
something like this. Can I do it?
I am trying to do it by mutate ifelse. But ifelse only allows one output variable. I can't do something for both a1 and a2.
Any suggestions? thanks a lot!
If general you'll have to do it with two ifelse functions inside the mutate. Or even better use dplyr::case_when which is much more flexible. If your conditional boolean expression is complicated you could calculate this first
df%>%
arrange(id,drugclass, start_date, end_date)%>%
group_by(id,drugclass)%>%
mutate(
cond = row_number == 1, # do it like this for complex conditions
a1 = case_when(
cond ~ a3,
TRUE ~ a5 # otherwise
),
a2 = case_when(
cond ~ a4,
TRUE ~ a6 # otherwise
)
)