R - 三元运算符的矢量化实现?

时间:2015-10-07 23:10:22

标签: r vectorization

标题说得尽可能好。我有什么:

A     B
TRUE  FALSE
FALSE TRUE
TRUE  TRUE

我想要的是什么:

C
if(A[1]&&B[1]){some.value.here}else if(A[1]){other.value}else{another.value}
if(A[2]&&B[2]){some.value.here}else if(A[2]){other.value}else{another.value}
if(A[3]&&B[3]){some.value.here}else if(A[3]){other.value}else{another.value}

我已经尝试了ifelse但只获得了原子结果而不是矢量。

3 个答案:

答案 0 :(得分:2)

如果您的数据框有两列,请尝试使用条件。

作为真实替代价值的占位符,我选择了"justA""justB""both"

df$result[df$A & df$B] <- "both"
df$result[df$A & !df$B] <- "justA"
df$result[df$B & !df$A] <- "justB"

df
      A     B result
1  TRUE FALSE  justA
2 FALSE  TRUE  justB
3  TRUE  TRUE   both
4 FALSE  TRUE  justB

数据

df <- data.frame(A=sample(c(T,F), 4, T), B=sample(c(T,F), 4, T))
df$result <- NA

答案 1 :(得分:2)

如果使用一点嵌套,使用ifelse可以正常工作。 (看到你试图弄清楚你哪里出错了会很高兴。)

A = c(TRUE, FALSE, TRUE)
B = c(FALSE, TRUE, TRUE)
C = ifelse(A & B, "both", ifelse(A, "A only", "not A"))
cbind(A, B, C)

#      A       B       C        
# [1,] "TRUE"  "FALSE" "A only" 
# [2,] "FALSE" "TRUE"  "not A"
# [3,] "TRUE"  "TRUE"  "both"  

答案 2 :(得分:0)

如果A和B是向量:

> A = c(TRUE, FALSE, TRUE)
> B = c(FALSE, TRUE, TRUE)

您可以使用mapply():

> mapply(function (x, y) ifelse(x && y, 1, 2), A, B)
[1] 2 2 1