Reputation: 737
I would like to test the following: for each value in x1
test if it falls between x2
and x3
. Basically if x2$x2
< x1
< x2$x3
is true return the values of x1
where it's true. In this case they will all be true. I am confused if I should write a function or if there is something inbuilt to do this?
x1 <- data.frame(x1=11:20, stringsAsFactors=FALSE)
> x1
x1
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
10 20
x2 <- 1:10
x3 <- 21:30
x2 <- data.frame(x2, x3, stringsAsFactors=FALSE)
> x2
x2 x3
1 1 21
2 2 22
3 3 23
4 4 24
5 5 25
6 6 26
7 7 27
8 8 28
9 9 29
10 10 30
Upvotes: 1
Views: 177
Reputation: 5537
Try the following:
x1$x1[which(x1$x1 > x2$x2 & x1$x1 < x2$x3)]
which
returns a vector of indices for which the equation (in this case, x1$x1 > x2$x2 & x1$x1 < x2$x3
holds true. We then select the right elements using x1$x1[indices]
.
Note the use of &
instead of &&
in the inequality, as you are working with vectors and not individual elements.
Upvotes: 2