Carbo
Carbo

Reputation: 916

R: find and set to zero each element in a vector that does not appear in another vector

I have two numeric vectors:

a <- c(1,2,3,4,5,6,7,8)
b <- c(4,2,2,3,9,10,7,7,10,14)

I want to set any number in b that does not appear in a to zero. My desired result is:

c <- c(4,2,2,3,0,0,7,7,0,0)

who can I do this in an elegant way?

(I was thinking to use left_join but I think there must be some more elegant approach)

Upvotes: 2

Views: 62

Answers (4)

akrun
akrun

Reputation: 886948

We can use replace

replace(b, !b  %in% a, 0)

Upvotes: 1

Cettt
Cettt

Reputation: 11981

You can do this by subsetting b with the %in% function:

b[! b %in% a] <- 0

Upvotes: 2

Sandy AB
Sandy AB

Reputation: 221

Use the negation of the %in% condition:

b[!b %in% a] <- 0

Upvotes: 2

Chuck P
Chuck P

Reputation: 3923

ifelse(b %in% a, b, 0) seems to do it.

Upvotes: 1

Related Questions