How to do if {multiple statements for multiple variables} within group_by data frame

Hello, all:
I am trying to do something like:

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!

Can you post a small sample of your data? The output of the command

dput(head(df))

would be very helpful. Simplifying the data to the minimum number of required columns would be best.

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
    )
  )

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.