R中是否存在三元运算符? [英] Does the ternary operator exist in R?
问题描述
正如问题所问,R中是否存在类似于C的三元运算符的控制序列?如果是这样,您如何使用它?谢谢!
As the question asks, is there a control sequence in R similar to C's ternary operator? If so, how do you use it? Thanks!
推荐答案
由于if
是R
中的函数,并且返回最新的求值,如果if-else等效于?:
.
As if
is function in R
and returns the latest evaluation, if-else is equivalent to ?:
.
> a <- 1
> x <- if(a==1) 1 else 2
> x
[1] 1
> x <- if(a==2) 1 else 2
> x
[1] 2
R的幂是矢量化.三元运算符的向量化为ifelse
:
The power of R is vectorization. The vectorization of the ternary operator is ifelse
:
> a <- c(1, 2, 1)
> x <- ifelse(a==1, 1, 2)
> x
[1] 1 2 1
> x <- ifelse(a==2, 1, 2)
> x
[1] 2 1 2
开个玩笑,您可以定义c样式?:
:
`?` <- function(x, y)
eval(
sapply(
strsplit(
deparse(substitute(y)),
":"
),
function(e) parse(text = e)
)[[2 - as.logical(x)]])
在这里,您无需注意括号:
here, you don't need to take care about brackets:
> 1 ? 2*3 : 4
[1] 6
> 0 ? 2*3 : 4
[1] 4
> TRUE ? x*2 : 0
[1] 2
> FALSE ? x*2 : 0
[1] 0
但是您需要用括号括起来:(
but you need brackets for assignment :(
> y <- 1 ? 2*3 : 4
[1] 6
> y
[1] 1
> y <- (1 ? 2*3 : 4)
> y
[1] 6
最后,您可以使用c进行非常相似的操作:
Finally, you can do very similar way with c:
`?` <- function(x, y) {
xs <- as.list(substitute(x))
if (xs[[1]] == as.name("<-")) x <- eval(xs[[3]])
r <- eval(sapply(strsplit(deparse(substitute(y)), ":"), function(e) parse(text = e))[[2 - as.logical(x)]])
if (xs[[1]] == as.name("<-")) {
xs[[3]] <- r
eval.parent(as.call(xs))
} else {
r
}
}
您可以删除括号:
> y <- 1 ? 2*3 : 4
> y
[1] 6
> y <- 0 ? 2*3 : 4
> y
[1] 4
> 1 ? 2*3 : 4
[1] 6
> 0 ? 2*3 : 4
[1] 4
这些不是日常使用,但可能对学习R语言的某些内部知识很有帮助.
These are not for daily use, but maybe good for learning some internals of R language.
这篇关于R中是否存在三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!