且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将间隔与R中另一个表中的值进行匹配

更新时间:2022-04-02 00:03:51

使用末尾注释"中可重复显示的数据,形成切点向量(即每个间隔中的第一个数字),然后使用 findInterval查找与权重相对应的间隔.

Using the data shown reproducibly in the Note at the end, form the vector of cutpoints (i.e. the first number in each interval) and then use findInterval to find the interval corresponding to the weight.

cutpoints <- as.numeric(sub("-.*", "", dfprice$wgt_intvl))
transform(dfmain, price = dfprice$price[findInterval(wgt, cutpoints)])

给予:

  Order wgt price
1    01  22    75
2    02   5    50
3    03  35   135
4    04  25   135

注意

dfmain <- data.frame(Order = c("01", "02", "03", "04"), wgt = c(22, 5, 35, 25), 
 stringsAsFactors = FALSE)

dfprice <- data.frame(wgt_intvl = c("0-15", "15-25", "25-50"), 
 price = c(50, 75, 135), stringsAsFactors = FALSE)