简体   繁体   English

在R中使用ifelse on factor

[英]Using ifelse on factor in R

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. 我想制作第3列,在可用时给出琐碎的名称,否则为拉丁名称。 Both trivial names and latin names are in factor-class. 琐碎的名字和拉丁名字都属于因子级。 I have tried with an if-loop: 我试过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. 它给了我正确的trivnames,但只在提供拉丁名字时给出了NA。
And when I use ifelse I only get numbers. 当我使用ifelse时,我只会得到数字。

As always, all help appreciated :) 一如既往,所有帮助赞赏:)

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...) (我认为默认选项(stringsAsFactors = FALSE)对大多数人来说会更容易,但是你去......)

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? 只获得数字表明你只需要在你的作业中添加as.character ,而if-else可能也可能你也似乎没有引用作业中的数据框?

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

Option 2: Using ifelse : 选项2:使用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 ... 它可能更容易(并且更多“R-thonic”,因为它避免了循环)只是将artname分配给artnametrivial ,然后用latname覆盖空白的...

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

If art2 is the dataframe, and artname the new column, another possible solution: 如果art2是数据artname是新列,则另一种可能的解决方案:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM