Nadina
Nadina

Reputation: 185

How to retrieve value from a data frame "between" two conditions

Can I get value between, for example x-1:x+1, from data frame in R?

if I have data.frame

A <- c(1,2,3,4,5,6,7,8)

B <- c(2,3,4,5,6,7,8,9)

and I have x = 2, how to get value that x-1 <= A <= x+1 so the result is

A B
1 2
2 3
3 4

Upvotes: 0

Views: 307

Answers (1)

gagolews
gagolews

Reputation: 13056

Let's see...

df <- data.frame(A=c(1,2,3,4,5,6,7,8), B=c(2,3,4,5,6,7,8,9))
x <- 2
df[df$A <= x+1 & df$A >= x-1,]
##   A B
## 1 1 2
## 2 2 3
## 3 3 4

Upvotes: 1

Related Questions