JNNYC
JNNYC

Reputation: 11

How to find closest match from list in R

I have a list of numbers and would like to find which is the next highest compared to each number in a data.frame. I have:

list <- c(3,6,9,12)
X <- c(1:10)
df <- data.frame(X)

And I would like to add a variable to df being the next highest number in the list. i.e:

X   Y
1   3
2   3
3   3
4   6
5   6
6   6
7   9
8   9
9   9
10  12

I've tried:

df$Y <- which.min(abs(list-df$X))

but that gives an error message and would just get the closest value from the list, not the next above.

Upvotes: 1

Views: 498

Answers (2)

Karolis Koncevičius
Karolis Koncevičius

Reputation: 9666

Another approach is to use findInterval:

df$Y <- list[findInterval(X, list, left.open=TRUE) + 1]

> df
    X  Y
1   1  3
2   2  3
3   3  3
4   4  6
5   5  6
6   6  6
7   7  9
8   8  9
9   9  9
10 10 12

Upvotes: 2

Andrew Gustar
Andrew Gustar

Reputation: 18445

You could do this...

df$Y <- sapply(df$X, function(x) min(list[list>=x]))

df
    X  Y
1   1  3
2   2  3
3   3  3
4   4  6
5   5  6
6   6  6
7   7  9
8   8  9
9   9  9
10 10 12

Upvotes: 1

Related Questions