if(x == y){
text <- "string_1"
}else if(x < y){
text <- "string_2"
}else if(x > y){
text <- "string_3"
}
有没有可能摆脱这些条款的方法?我们可以使用任何数学运算来找出答案吗?
我真的没有说出解决您问题的方法。不过,您可以编写得更简洁一些。
if(x == y) text <- "string_1"
if(x < y) text <- "string_2"
if(x > y) text <- "string_3"
答案是:是的,您可以在没有控制语句的情况下完成它。
您可以尝试以下代码
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)]