user434180
user434180

Reputation: 805

Filter vector based on parellel vector

Suppose I have two vectors:

x = c(1,2,3,4,5,6,7,8,9,10)
y = c(1,2,3,1,2,3,1,2,3,2)

I want to produce a new list that has all the elements of x in it such that the corresponding element in y meets a condition. For example, suppose I want all elements in x, denoted x[i] such that y[i], = 2. So in this case I want the new list to be x' = [2,5,8,10].

Its obvious how to do this slowly by brute force, but I wonder if there is a fast and/or syntactically concise way of doing this in R.

Thanks!

Upvotes: 2

Views: 39

Answers (1)

www
www

Reputation: 39174

x <- c(1,2,3,4,5,6,7,8,9,10)
y <- c(1,2,3,1,2,3,1,2,3,2)

z <- x[y == 2]
z
# [1]  2  5  8 10

Upvotes: 2

Related Questions