jjordan
jjordan

Reputation: 42

Join 2 columns based on logical 3rd column

I have 3 vectors as follows:

a <- c(1,2,3,4,5,6,7,8,9,10)
b <- c(10,20,30,40,50,60,70,80,90,100)
c <- c(TRUE,TRUE,TRUE,TRUE,TRUE,FALSE,FALSE,FALSE,FALSE,FALSE)

I would like to generate a new vector, in which observations from 'a' are used when c is TRUE and observations from 'b' are used when c is FALSE. Results would show as:

d <- c(1,2,3,4,5,60,70,80,90,100)

Upvotes: 1

Views: 47

Answers (3)

akrun
akrun

Reputation: 887881

Another option is row/column indexing

cbind(a, b)[cbind(seq_along(c), (!c)+1)]
#[1]   1   2   3   4   5  60  70  80  90 100

Or with pmax

pmax(a*c, b*!c)
#[1]   1   2   3   4   5  60  70  80  90 100

Upvotes: 0

Kevin Arseneau
Kevin Arseneau

Reputation: 6264

A relatively simple problem, I would be surprised if this is not a duplicate.

library(dplyr)

df <- tibble(
  a = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
  b = c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100),
  c = c(TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)
)

df <- df %>%
  mutate(d = if_else(c, a, b))

df

# # A tibble: 10 x 4
#       a     b     c     d
#   <dbl> <dbl>  <lgl> <dbl>
# 1     1    10   TRUE     1
# 2     2    20   TRUE     2
# 3     3    30   TRUE     3
# 4     4    40   TRUE     4
# 5     5    50   TRUE     5
# 6     6    60  FALSE    60
# 7     7    70  FALSE    70
# 8     8    80  FALSE    80
# 9     9    90  FALSE    90
# 10    10   100 FALSE   100

Upvotes: 1

Marius
Marius

Reputation: 60190

This can be done easily with ifelse:

d <- ifelse(c, a, b)

Upvotes: 3

Related Questions