正如问题所问,R中是否存在一个类似于C的三元算子的控制序列?如果有,你如何使用它?谢谢!
当前回答
我会看一下ifelse命令。我认为它更好,因为它也是向量化的。一个使用cars数据集的例子:
> cars$speed > 20
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[25] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[37] FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
[49] TRUE TRUE
> ifelse(cars$speed > 20, 'fast', 'slow')
[1] "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow"
[11] "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow"
[21] "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow"
[31] "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow" "slow"
[41] "slow" "slow" "slow" "fast" "fast" "fast" "fast" "fast" "fast" "fast"
其他回答
If的工作方式类似于未向量化的ifelse,如果按以下方式使用:
`if`(condition, doIfTrue, doIfFalse)
使用这个优于ifelse的优势是当向量化是在路上(即我有标量布尔和列表/向量的东西作为结果)
ifelse(TRUE, c(1,2), c(3,4))
[1] 1
`if`(TRUE, c(1,2), c(3,4))
[1] 1 2
就像if是R中的函数并返回最新的求值一样,if-else等价于?:。
> a <- 1
> x <- if(a==1) 1 else 2
> x
[1] 1
> x <- if(a==2) 1 else 2
> x
[1] 2
R的幂是向量化。三元运算符的向量化是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)]])
在这里,你不需要考虑括号:
> 1 ? 2*3 : 4
[1] 6
> 0 ? 2*3 : 4
[1] 4
> TRUE ? x*2 : 0
[1] 2
> FALSE ? x*2 : 0
[1] 0
但你需要括号赋值:(
> y <- 1 ? 2*3 : 4
[1] 6
> y
[1] 1
> y <- (1 ? 2*3 : 4)
> y
[1] 6
最后,你可以用类似的方法来处理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语言的一些内部知识。
我写了一个小的语言扩展,它在r中模拟C的条件三元运算符。它可以作为一个包从这里安装
实现是基于@kohske给出的答案,但我做了一些更改,使其健壮到if_true和if_false参数包含冒号的情况下,允许条件语句被链接,并保留的基本功能?操作符。
我将参考其他人关于重新定义操作符的危险的警告,但这是R语言可以多么动态的一个很好的例子!
你的链接指向一个if语句。
> x <- 1
> if(x < 2) print("Less than") else print("Greater than")
[1] "Less than"
如果你的输入变量是一个向量,那么ifelse可能更适合:
> x <- 1:3
> ifelse(x<=2, "Less than or equal", "Greater than")
[1] "Less than or equal" "Less than or equal" "Greater than"
要访问if的帮助页面,你需要在反引号中嵌入if:
?`if`
ifelse的帮助页面在:
`?ifelse`
它并不明确存在,但你可以这样做:
set.seed(21)
y <- 1:10
z <- rnorm(10)
condition1 <- TRUE
x1 <- if(condition1) y else z
or
condition2 <- sample(c(TRUE,FALSE),10,TRUE)
x2 <- ifelse(condition2, y, z)
两者之间的区别在于,condition1必须是长度为1的逻辑向量,而condition2必须是与x、y和z长度相同的逻辑向量。第一个将返回y或z(整个对象),而第二个将返回y (condition2==TRUE)或z (condition2==FALSE)的对应元素。
还要注意,ifelse将比if / else if条件慢,y和z都是长度为1的向量。