0

So i tried an if else statement but failed...

(I am working with string columns, in R)

hostpairs["hostspecificity"] <- NA

If (hostpairs$hostgenus2 == NA){
  hostpairs$hostspecificity == 0
} else if(hostpairs$hostgenus1 == hostpairs$hostgenus2){
  hostpairs$hostspecificity == 1
} else {
  hostpairs$hostspecificity == 2
}

Error in if (hostpairs$hostgenus2 == NA) { :
missing value where TRUE/FALSE needed
In addition: Warning message:
In if (hostpairs$hostgenus2 == NA) { : the condition has length > 1 and only the first element will be used

I am pretty sure there is a pretty dumb mistake somewhere in there...

ps. Also if there is a function that checks two string column row by row and comes up with TRUE if they are equal (case insensitive, John = JOHN) or FALSE if they are not equal (John != Mary) That would be very helpful!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Kostas Daglis
  • 39
  • 1
  • 1
  • 5
  • Use `ifelse` rather than `if`. – lmo Jun 28 '17 at 17:55
  • what is the difference? and how do i add **else ifs** in ifelse? – Kostas Daglis Jun 28 '17 at 17:58
  • `ifelse` acts on vectors whereas `if` will only work on vectors of length 1 (AKA scalars). To get multiple levels, you nest `ifelse`. So try `ifelse(x == 1, 1, ifelse(x == 2, 2, 0))` on `x <- -2:2` for a simple example and see `?ifelse` and `?"if"` for a discussion of these functions. – lmo Jun 28 '17 at 18:02
  • OK! this works for comparing two string columns right? – Kostas Daglis Jun 28 '17 at 18:05
  • Yes. Better to compare string columns than factor columns, so make sure that is true with `str(hostpairs)`. If they are factors, convert them to strings (character vectors) using `hostpairs$varname <- as.character(hostpairs$varname)` on each of them and then do the comparison. – lmo Jun 28 '17 at 18:07
  • OK! Thanks a lot!! :) – Kostas Daglis Jun 28 '17 at 18:09

0 Answers0