【发布时间】:2014-06-11 22:46:05
【问题描述】:
在下面的示例中,逻辑向量!is.na(X) 和!is.na(Y) 通过预乘一个整数被强制转换为数字,然后相加。但结果看起来好像“+”被解释为 XOR。谁能解释为什么会这样?
set.seed(1)
X <- sample(c(NA,1),10,replace=T)
Y <- sample(c(NA,1),10,replace=T)
2*!is.na(X) # numeric, as expected
# [1] 0 0 2 2 0 2 2 2 2 0
2*!is.na(Y) # numeric, as expected
# [1] 0 0 2 0 2 0 2 2 0 2
2*!is.na(X) + 2*!is.na(Y) # huh?
# [1] 0 0 0 2 0 2 0 0 2 0
# but this works...
xx <- 2*!is.na(X)
yy <- 2*!is.na(Y)
xx+yy
# [1] 0 0 4 2 2 2 4 4 2 2
# as does this...
as.numeric(2*!is.na(X)) + 2*!is.na(Y)
# [1] 0 0 4 2 2 2 4 4 2 2
# and this...
2*(!is.na(X)) + 2*(!is.na(Y))
# [1] 0 0 4 2 2 2 4 4 2 2
在新的会话中运行。 R 版本 3.0.3 (2014-03-06),Win 7 x64
【问题讨论】:
-
两个字:运算符优先级。
-
线索:
2*!is.na(X) + 3*!is.na(Y)
标签: r