匹配间隔与 R 中另一个 table 中的值

Matching intervals with values in another table in R

目前,我有一个 df 和一个价格 table。

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

我想要的是将 df 的权重匹配到 R 中价格 table 的区间。例如,第一个订单 (Order Number 01) 对应的价格是75. 因此,我想在第一个df中添加一列,说df$cost根据价格table中的wgt_intvl对应合适的价格。

我看到的方法是使用 if-else 语句,但这是非常低效的,我想知道是否有更好的方法来做到这一点。实际上,这些 table 更长 - 价格或重量区间没有逻辑上的 "buildup"。我在这个 table 中有 15 个权重区间。我当前的解决方案如下所示:

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

这次十五次,使用价格table对应的价格。我想要一个更有效的解决方案。提前致谢!

您可以使用更高效的 case_when 操作来代替 if 语句:

library(dplyr)
 df %>%
mutate(cost = case_when(
    wgt < 15 ~ 50,
    wgt > 15 & wgt <25 ~ 75,
    TRUE ~ 135))

或者,您可以使用 cut() 将 wgt 转换为 wgt_intvl 并通过 left_join() 进行匹配。

使用最后注释中可重复显示的数据,形成切点向量(即每个区间中的第一个数字),然后使用 findInterval 找到与权重对应的区间。

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)