2015-10-07 24 views
0

標題說得很好,我也可以。我有什麼:R - 三元運算符的矢量化實現?

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,但只得到了原子結果並不載體。

+0

這是一個數據框,A和B是一部分嗎? –

+0

不,A和B本身就是矢量。 –

回答

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" 
+1

我用'ifelse(A && B,「Both」,ifelse(A,「Just A「,」Not A「))'我現在認識到的是使用'&&'代替'&'的錯誤b/c。 –

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 
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 
+0

對不起,剛纔注意到你的邏輯性質。您需要使用嵌套的'ifelse',例如(x,y)ifelse(x,ifelse(y,1,3),2),A,B)' –