Joe
Joe

Reputation: 1768

How to subset a vector by indices given in another vector?

I have two vectors of equal length, one containing numeric values (num_vec), the other containing only zeros and ones (bool_vec). My goal is to keep all values in num_vec with indices that correspond to ones in bool_vec. Here is an example:

num_vec <- c(1:5)
bool_vec <- c(0, 0, 1, 0, 1)

The output should be:

> output
[1] 3 5

How to do it?

Upvotes: 1

Views: 401

Answers (1)

akrun
akrun

Reputation: 886938

We just need to convert the binary to logical with as.logical so that 1 converts to TRUE and 0 to FALSE. Then use that index to subset the vector

num_vec[as.logical(bool_vec)]

Upvotes: 4

Related Questions