Xelm
Xelm

Reputation: 3

R: Compare vectors of differing lengths

I'm actually having trouble phrasing my question, so if anyone has feedback on that, I'd love to hear it.

I'm working in R and have a vector and a data frame, of different lengths:

xp.data <- c(400,500,600,700)
XPTable <- data.frame("Level"=1:10,"XP"=c(10,50,100,200,400,600,700,800,900,1000))

What I'm hoping to obtain is a new vector:

> lv.data
[1] 5 5 6 7

The goal is to do so without using a loop, as the xp.data vector can be any length, and the XPTable data frame can also be of varying lengths.

If I was doing this without a vector for xp.data, I'd just use:

max(XPTable$Level[XPTable$XP < XP.data])

However, this only works if XP.data has a length of 1.

Upvotes: 0

Views: 46

Answers (1)

12b345b6b78
12b345b6b78

Reputation: 1015

    lv.data <- findInterval(xp.data, XPTable$XP)
    print(lv.data)
    # [1] 5 5 6 7

Upvotes: 2

Related Questions