不使用R中的任何控制语句检查条件的任何可能方法 if(x==y){ text

不使用R中的任何控制语句检查条件的任何可能方法 if(x==y){ text,r,if-statement,R,If Statement,答案是:是的,你可以不使用控制语句 您可以尝试以下代码 if(x == y){ text <- "string_1" }else if(x < y){ text <- "string_2" }else if(x > y){ text <- "string_3" } r我真的没有办法解决你的问题(对我来说,问题似乎是难看的代码)。不过,你可以把它写得更简洁 r <- c("string_1","string_2","string_3")[cross

答案是:是的,你可以不使用控制语句

您可以尝试以下代码

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

r我真的没有办法解决你的问题(对我来说,问题似乎是难看的代码)。不过,你可以把它写得更简洁

r <- c("string_1","string_2","string_3")[crossprod(diag(+c(x==y,x<y,x>y)), 1:3)]

如果(x==y)文本使用
data.table
可以执行以下操作:

if(x == y) text <- "string_1"
if(x < y) text <- "string_2" 
if(x > y) text <- "string_3"
库(data.table)
fcase(
x==y,“字符串_1”,
x

截至2020年1月,此功能仍仅在软件包的开发版本中。

您可以使用
符号
为条件
=
的向量子集


text
text我很抱歉没有把问题说清楚,我在下一篇文章中会记住这一点非常感谢你的帮助我无法使用库来解决这个简单的问题无论如何,非常感谢你宝贵的时间
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"
library(data.table)
fcase(
  x == y, "string_1",
  x <  y, "string_2",
  default = "string_3"
)
text <- c("string_2", "string_1", "string_3")[sign(x-y)+2]