将间隔与R中另一个表中的值进行匹配 [英] Matching intervals with values in another table in R

查看:101
本文介绍了将间隔与R中另一个表中的值进行匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有一个df和价格表.

Currently, I have one df and a price table.

Order Number  wgt           wgt_intvl        price
-------------------         ---------------  -----
 01            22           0-15             50
 02            5            15-25            75
 03            35           25-50            135

我想要的是将df中的权重匹配到R中价格表的间隔中.例如,第一笔订单( Order Number 01 )对应价格为75因此,我想在第一个df中添加一列,例如 df $ cost ,该列与根据价格表中的 wgt_intvl 适当的价格相对应.

What I'd like is to match the weight from the df into an interval of the price table in R. For example, the first order (Order Number 01) corresponds with a price of 75. Therefore, I want to add a column in the first df, say df$cost that corresponds with the appropriate price according to wgt_intvl in the price table.

我看到的方法是使用 if-else 语句,但这效率很低,我想知道是否有更好的方法可以做到这一点.实际上,这些表要长得多-价格或权重区间没有逻辑上的累积".我在这张桌子上有15个体重间隔.我当前的解决方案如下所示:

The way I see to do it is with an if-else statement, but this is highly inefficient and I was wondering if there is a better way to do it. In reality these tables are much longer - there is no logical "buildup" in price or weight interval. I have 15 weight intervals in this table. My current solution would look like this:

If(wgt < 15){
  df$cost <- 50
} else if (wgt > 15 & wgt < 25){ 
  df$cost <- 75
} else if(wgt > 25 & wgt < 50){ 
  df$cost <- 135
} 

使用价格表中的相应价格,这是十五次.我希望有一个更有效的解决方案.提前致谢!

This times fifteen, using the corresponding prices of the price table. I'd love a more efficient solution. Thanks in advance!

推荐答案

使用末尾注释"中可重复显示的数据,形成切点向量(即每个间隔中的第一个数字),然后使用 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)

这篇关于将间隔与R中另一个表中的值进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆