Camden Narzt
Camden Narzt

Reputation: 2003

R - Vectorized implementation of ternary operator?

The title says it about as well as I can. What I have:

A     B
TRUE  FALSE
FALSE TRUE
TRUE  TRUE

what I want:

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}

I've tried ifelse but only got atomic results not vectors.

Upvotes: 0

Views: 513

Answers (3)

Gregor Thomas
Gregor Thomas

Reputation: 145785

Using ifelse works fine if with a little nesting. (It would have been nice to see your attempt to figure out where you went wrong.)

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"  

Upvotes: 3

Pierre L
Pierre L

Reputation: 28441

If you have a data frame with two columns, try using conditionals.

As a placeholder for your real replacement values, I chose "justA", "justB", and "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

Data

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

Upvotes: 2

Mark Schaschke
Mark Schaschke

Reputation: 46

If A and B are vectors:

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

You can use mapply():

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

Upvotes: 0

Related Questions