简体   繁体   English

R中的ifelse行为

[英]ifelse behaviour in R

First of all I declare that I checked all the related question on ifelse , but without any success. 首先,我声明我检查了ifelse上的所有相关问题,但没有成功。 I am trying to use ifelse to add a factor (mating period) in wildlife species according to the months. 我正在尝试使用ifelse根据月份在野生动植物物种中添加一个因子(交配期)。 An example of the DB is below: 该数据库的示例如下:

> DB <- data.frame(ID = 1:6, Month = 1:12)
colnames(DB) <- c("ID","Month")

What I have tried is: 我试过的是:

Period<-with(DB,ifelse(Month==c(2,3,4,5,6,7,8,9,10),"M","R")))

but the result doesn't match the condition: 但结果不符合条件:

(Period)[1] "R" "R" "R" "R" "R" "R" "R" "R" "R" "R" "R" "R"

and there is also a warning: 还有一个警告:

Warning message:
In Month == c(2, 3, 4, 5, 6, 7, 8, 9, 10) :
longer object length is not a multiple of shorter object length`

Surprisingly, when I launch the script on the real DB two things happen: 令人惊讶的是,当我在真实的数据库上启动脚本时,会发生两件事:

  • In the new column Period some M appears 在新的“期间”栏中,出现一些M
  • No warning comes out 没有警告发出

I am now really confused on how ifelse works. 我现在对ifelse工作方式感到困惑。 I hope someone could clarify how this function works and how properly type the script to obtain the correct result. 我希望有人能阐明此功能的工作原理以及如何正确键入脚本以获得正确的结果。

Use %in% as in: 使用%in%如下所示:

Period<-with(DB,ifelse(Month %in% c(2,3,4,5,6,7,8,9,10),"M","R"))
Period
 [1] "R" "M" "M" "M" "M" "M" "M" "M" "M" "M" "R" "R"

Your comparison is of the wrong form. 您的比较格式错误。 ifelse goes through one element at a time making the comparison whereas Month == 2:10 will pairwise compare the elements and return a vector indicating whether each pairwise comparison is true or false. ifelse一次比较一个元素,而Month == 2:10将成对比较元素并返回一个向量,该向量指示每个成对比较是对还是对。

You want to use %in% which returns true or false depending on whether an element is in a vector: 您想使用%in% ,根据元素是否在向量中,该值返回true或false:

Period<-with(DB,ifelse(Month %in% 2:10,"M","R")))

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

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