Using ifelse on factor in R

社会主义新天地 提交于 2019-12-22 06:32:40

问题


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 :)


回答1:


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...)




回答2:


Getting only numbers suggests that you just need to add as.character to your assignments, and the if-else would probably work you also seem to not be referring to the data frame in the assignment?

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

Option 2: Using ifelse:

 art2$artname= ifelse(as.character(art2$trivname) == "", as.character(art2$latname),as.character(art2$trivname))

It is probably easier (and more "R-thonic" because it avoids the loop) just to assign artname to trivial across the board, then overwrite the blank ones with latname...

art2 = art
art2$artname = as.character(art$trivname)
changeme = which(art2$artname=="")
art2$artname[changeme] = as.character(art$latname[changeme])



回答3:


If art2 is the dataframe, and artname the new column, another possible solution:

art2$artname <- as.character(art2$trivname)
art2[art$artname == "",'artname'] <- as.character(art2[art2$artname == "", 'latname'])

And if you want factors in the new column:

art2$artname <- as.factor(art2$artname)


来源:https://stackoverflow.com/questions/11275120/using-ifelse-on-factor-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!