If/Else multilevel variable creation

Hi! For some reason, this is throwing errors and saying I'm missing parentheses or comma depending on what I do. Any suggestions or adjustments would be much appreciate.

Existing code:

dx <- tibble::tribble(
~PSQI3_hr_PSQI3_5, ~PSQI3_AMPM_PSQI3_5, ~PSQI4_hr_PSQI4_5, ~PSQI4_AMPM_PSQI4_5,
"9", "1", "11", "1",
"8", "1", "8", "1",
"10", "1", "12", "2",
"5", "1", "5", "1",
"9", "1", "9", "1",
"6", "1", "5", "2"
)

dx <- mutate(SFSWeekday = ifelse(((dx$PSQI3_hr_PSQI3_5 == dplyr::between(left = 6, right = 9)) & dx$PSQI3_AMPM_PSQI3_5 == "AM"), 3,
ifelse((dx$PSQI3_hr_PSQI3_5 == dplyr::between(left = 9, right = 11)) & dx$PSQI3_AMPM_PSQI3_5 == "AM"), 2,
ifelse((dx$PSQI3_hr_PSQI3_5 == dplyr::between(left = 12, right = 1)) & dx$PSQI3_AMPM_PSQI3_5 == "PM"), 1, 0)
SFSWeekend = ifelse(((dx$PSQI4_hr_PSQI4_5 == dplyr::between(left = 6, right = 9)) & dx$PSQI4_AMPM_PSQI4_5 == "AM"), 3,
ifelse((dx$PSQI4_hr_PSQI4_5 == dplyr::between(left = 9, right = 11)) & dx$PSQI4_AMPM_PSQI4_4 == "AM"), 2,
ifelse((dx$PSQI4_hr_PSQI4_5 == dplyr::between(left = 12, right = 1)) & dx$PSQI4_AMPM_PSQI4_5 == "PM") 1, 0))

Thank you!

I am not sure what you are trying to do. You have some conditionals that always evaluate to false like:
dx$PSQI3_AMPM_PSQI3_5 == "AM" and PSQI3_AMPM_PSQI3_5 == "PM"

None of the data in your table take either of these values.

Also, you are missing an argument to dplyr::between() which takes x, left, and right.

I think you can re-write this much more clearly and concisely using dplyr::case_when() rather than nested ifelse() statements. The format is as follows:

dx <- mutate(
  SFSWeekday = case_when(
    condition1 ~ value1,
    condition2 ~ value2,
    condition3 ~ value3,
    TRUE ~ value4
  )
)

You can have an arbitrary number of conditions, and the last line allows you to specify a default/fallback value if none of the preceding conditions are met.

1 Like

Thank you!

I tried to rewrite it like this:

dx <- mutate(
SFSWeekday = case_when(
PSQI3_hr_PSQI3_5 < 9 & PSQI3_AMPM_PSQI3_5 == "AM" ~ 3,
PSQI3_hr_PSQI3_5 == 9:11 & PSQI3_AMPM_PSQI3_5 == "AM" ~ 2,
PSQI3_hr_PSQI3_5 == 12:1 & PSQI3_AMPM_PSQI3_5 == "PM" ~ 1,
TRUE ~ 0
))

It's not running yet, so I guess maybe I'm still off? I took a look at the documentation before doing this...I've been working with R for a while but never been good at data wrangling. I very much appreciate the help!

This might make sense if PSQI3_hr_PSQI3_5 could take the value c(9,10,11) but I'm guessing it probably can't and your intent is to match if it's a single value from within the set of 3 values, if so change

PSQI3_hr_PSQI3_5 == 9:11

to

PSQI3_hr_PSQI3_5 %in% 9:11
1 Like

Thank you very much!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.