无需使用R中的任何控制语句即可检查条件的任何方法

问题描述 投票:0回答:2
if(x == y){
  text <- "string_1"
}else if(x < y){
  text <- "string_2"
}else if(x > y){
  text <- "string_3"
}

有没有可能摆脱这些条款的方法?我们可以使用任何数学运算来找出答案吗?

r
2个回答
0
投票

我真的没有说出解决您问题的方法。不过,您可以编写得更简洁一些。

if(x == y) text <- "string_1"
if(x < y) text <- "string_2" 
if(x > y) text <- "string_3"

0
投票

答案是:是的,您可以在没有控制语句的情况下完成它。

您可以尝试以下代码

r <- c("string_1","string_2","string_3")[c(x==y,x<y,x>y)]

r <- subset(c("string_1","string_2","string_3"), c(x==y,x<y,x>y))

r <- c("string_1","string_2","string_3")[crossprod(diag(+c(x==y,x<y,x>y)), 1:3)]
© www.soinside.com 2019 - 2024. All rights reserved.