简体   繁体   English

如何在 r 中编写一个条件(如果,ifelse)来选择向量的一个或多个元素?

[英]How to program a condition (if, ifelse) in r that chooses one or more elements of a vector?

How to program a condition in r that chooses one or two elements of a vector?如何在 r 中编写一个选择向量的一个或两个元素的条件? I tried to use ifelse() but it demands to have the same length both in test and yes , no arguments.我尝试使用ifelse()但它要求在测试中具有相同的长度, yes的, no arguments。

 object <- sample(c("A","B","C"),1)

ifelse(object %in% c("A","A"), c(1,2),

       ifelse(object=="B", 1,

              ifelse(object=="C",2,NaN)))

I want to obtain 1,2 when object is "A"当 object 为"A"时,我想获得1,2

If the object is of length 1, we can use if/else如果 object 的length 1,我们可以使用if/else

f1 <- function(obj) if(obj == 'A') 1:2 else if(obj == 'B') 1 else if(obj == 'C') 2 else NaN
f1(object)
#[1] 1 2

Or with switch或带switch

f2 <- function(obj) switch(obj, 'A' = 1:2, 'B' = 1, 'C' = 2,  NaN)

f2(object)
#[1] 1 2

f2('B')
#[1] 1
f2('C')
#[1] 2

f2('D')
#[1] NaN

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

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