-1

I am trying to create binary variable inside the readmitted column in R :

enter image description here

if the value is is <30 then the the variable should = YES and anything else should = NO. This is the code I have but I am not sure how to get the else values.

HospitalData$readmitted <-  case_when(HospitalData$readmitted <30 ~ "YES" )
Feverish123
  • 105
  • 1
  • 7
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. No not post images of data. It looks like your readmitted column is a character value, not numeric, so maybe try `case_when(HospitalData$readmitted == "<30" ~ "YES" )` – MrFlick Apr 22 '21 at 21:54
  • Sorry, the column was already present with these values before my code. When I try my code, It only replaces the values that are <30 with YES and N/A's everything else. I want everything that is not <30 to equal to NO – Feverish123 Apr 22 '21 at 21:57
  • 1
    Then add `case_when(HospitalData$readmitted == "<30" ~ "YES", TRUE~"NO")` for all the other values. – MrFlick Apr 22 '21 at 21:58
  • Yes, that was what I was looking for, thank you! – Feverish123 Apr 22 '21 at 21:59
  • 1
    Since you have only two cases, `if_else` may be more simple: `if_else(HospitalData$readmitted == "<30", "YES", "NO")` – MrFlick Apr 22 '21 at 22:00

1 Answers1

2

This is pretty fast in data.table:

library(data.table)
HospitalData <- setDT(HospitalData)
HospitalData[,readmitted:=ifelse(readmitted == "<30", "YES", "NO")]
Gabe Solomon
  • 365
  • 3
  • 12