Using ifelse on factor in R

ego_ picture ego_ · Jun 30, 2012 · Viewed 24.6k times · Source

I am restructuring a dataset of species names. It has a column with latin names and column with trivial names when those are available. I would like to make a 3rd column which gives the trivial name when available, otherwise the latin name. Both trivial names and latin names are in factor-class. I have tried with an if-loop:

  if(art2$trivname==""){  
    art2$artname=trivname   
    }else{  
      art2$artname=latname  
    }  

It gives me the correct trivnames, but only gives NA when supplying latin names.
And when I use ifelse I only get numbers.

As always, all help appreciated :)

Answer

Allan Engelhardt picture Allan Engelhardt · Aug 8, 2012

Example:

art <- data.frame(trivname = c("cat", "", "deer"), latname = c("cattus", "canis", "cervus"))
art$artname <- with(art, ifelse(trivname == "", as.character(latname), as.character(trivname)))
print(art)
#   trivname latname artname
# 1      cat  cattus     cat
# 2            canis   canis
# 3     deer  cervus    deer

(I think options(stringsAsFactors = FALSE) as default would be easier for most people, but there you go...)