Finding all values in a vector that lie within a range in R

r

#1

Hello,

I need to find all the values in a vector that lie within a particular range in R.
Example:
I have a dataframe which has values from 1:10.

Wanted to know if there is something like 2 < x < 8 in R??


#2

hello @pagal_guy,

There is a package called “TeachingDemos” in R using which you can do:




#3

When you write, 2<x<8
You can re-write it in the form of two conditions, x>2 and x<8
you can get the result required simply using

subset(vec ,x>2 & x<8)


#4

The %in% operator is your friend.

df = data.frame(a = 1:20, b = 45:64)
head(df)
a b
1 1 45
2 2 46
3 3 47
4 4 48
5 5 49
6 6 50
new_df = subset(df, a %in% 7:11)
new_df
a b
7 7 51
8 8 52
9 9 53
10 10 54
11 11 55