if(x == y){
text <- "string_1"
}else if(x < y){
text <- "string_2"
}else if(x > y){
text <- "string_3"
}
有什么可能的方法可以摆脱这些条款吗? 我们可以使用任何数学运算来找出答案吗?
您可以使用sign
来为条件==
、<
和>
的向量子集。
text <- c("string_2", "string_1", "string_3")[sign(x-y)+2]
答案是:是的,你可以在没有控制语句的情况下做到这一点。
您可以尝试以下代码
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)]
我真的看不出解决你的问题的方法(对我来说,问题似乎是丑陋的代码(。不过,你可以写得更简洁。
if(x == y) text <- "string_1"
if(x < y) text <- "string_2"
if(x > y) text <- "string_3"
使用data.table
你可以做到:
library(data.table)
fcase(
x == y, "string_1",
x < y, "string_2",
default = "string_3"
)
截至 2020 年 1 月,此功能仍仅在包的开发版本中提供。