0

I'm new to R. I want to do something along the lines of:

if Survive="Y" then Survive1=1 in my dataframe named "od" But, I'm having trouble with the code. This is what I currently have

od$Survive <- c(0)
if(od$Survive=="Y"){
  od$Survive1=1
}

I keep getting this warning:

Warning message: In if (od$Survive == "Y") { : the condition has length > 1 and only the first element will be used

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
help
  • 53
  • 1
  • 8

1 Answers1

2

The error you are seeing has to do with that an if statement is not vectorized, and so R is telling you that only the first element of the vector will be used. Try using ifelse for a vectorized solution:

od$Survive1 <- ifelse(od$Survive == "Y", 1, 0)

You could also just assign to the boolean expression:

od$Survive1 <- od$Survive == "Y"
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360