问题描述
我正在重组物种名称的数据集。它有一个带有拉丁名称的列和具有琐碎名称的列,当这些可用时。我想制作第3列,在可用时给出简单的名称,否则为拉丁名称。琐碎的名字和拉丁名字都属于因子级。
我试过if-loop:
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
}
它给了我正确的trivnames,但只在提供拉丁名字时给出NA。
当我使用ifelse时我只得到数字。
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 :)
推荐答案
示例:
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
(我认为默认选项(stringsAsFactors = FALSE)对大多数人来说会更容易,但是你去......)
(I think options(stringsAsFactors = FALSE) as default would be easier for most people, but there you go...)
这篇关于在R中使用ifelse on factor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!