Paul
Paul

Reputation: 696

Replace values corresponding to vector with 0

I have a large vector

LVector <- c(1:17649) 

I need to keep the following values and overwrite all others with 0.

Keeps <-c(1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000)

This is what i have tried so far:

LVector <- c(1:17649)
LVectorTEMP <- LVector
Keeps <-c(1000,2000,3000,4000,5000,6000,7000,8000,9000,10000,11000,12000,13000,14000,15000,16000,17000)
LVectorTEMP <- LVectorTEMP[! LVectorTEMP %in% Keeps]

### At this point I have created a vector which has all of the numbers I want to replace with 0.

I tried variations of this

result <- LVector[LVector==LVectorTEMP] <- 0

and this

result <- LVector[0 LVector %in% LVectorTEMP]

But they do not work.

I am sure there is a simple way to do this but searching hasn't revealed the answer yet this morning. Thanks for your help!

Upvotes: 0

Views: 53

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

I've tried a variation of one of your attempts but with smaller vectors, in order to better see what's going on and as far as I can see it works.

k <- c(2, 4, 6)
lv <- 1:10
lv[!lv %in% k] <- 0
lv
[1] 0 2 0 4 0 6 0 0 0 0

Upvotes: 1

xtluo
xtluo

Reputation: 2121

Try:

LVector <- ifelse(LVector %in% Keeps, LVector, 0)

Upvotes: 0

Related Questions