【问题标题】:Adding two vectors coerced from logical to numeric [duplicate]添加两个从逻辑强制转换为数字的向量
【发布时间】: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


【解决方案1】:

这可能是您所期望的:

 (2*!is.na(X)) + (2*!is.na(Y))
 #[1] 0 0 4 2 2 2 4 4 2 2

你的被解析为:

 2*!( is.na(X) + 2*!is.na(Y) )
 [1] 0 0 0 2 0 2 0 0 2 0

【讨论】:

    猜你喜欢
    • 2013-06-20
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多