首页 > 解决方案 > 基于R中第二个数据帧中的范围计算的字段

问题描述

我发现了有关此任务的类似帖子,但所有这些帖子都有一个共同的 ID 连接这两个表。

我有一个包含销售记录(sales_df)的数据框。对于此示例,我简化了数据表,使其仅包含 5 条记录。我想在 sales_df 中创建一个新列,用于计算费用表中定义的销售价格金额(pricing_fees)。请注意,我必须考虑的实际定价费用范围的数量约为 30,因此将其写入 mutate 语句是我想尽量避免的事情。

两个数据帧编码如下

    sales_df <- data.frame(invoice_id = 1:5, 
sale_price = c(100, 275, 350, 500, 675))

    pricing_fees <- data.frame(min_range = c(0, 50, 100, 200, 300, 400, 500), # >=
    max_range = c(50, 100, 200, 300, 400, 500, 1000), # <
    buyer_fee = c(1, 1, 25, 50, 75, 110, 125))

最后,我希望得到的 sales_df 看起来像这样。

  invoice_id sale_price buyer_fee
1          1        100        25
2          2        275        50
3          3        350        75
4          4        500       125
5          5        675       125

提前致谢

标签: rdataframemerge

解决方案


您可以使用findInterval应该在范围内有效分割值的函数(因为它使用二进制搜索):

# build consecutive increasing ranges of fees 
# (in order to use findInterval, since it works on ranges defined in a single vector)
pricing_fees <- pricing_fees[order(pricing_fees$min_range),]
consecFees <- data.frame(ranges=c(pricing_fees$min_range[1], pricing_fees$max_range),
                         fees=c(pricing_fees$buyer_fee,NA))
# consecFees now is :
#
#   ranges fees
# 1      0    1  ---> it means for price in [0,50) -> 1
# 2     50    1  ---> it means for price in [50,100) -> 1
# 3    100   25  ---> it means for price in [100,200) -> 25
# 4    200   50  ... and so on
# 5    300   75
# 6    400  110
# 7    500  125
# 8   1000   NA ---> NA because for values >= 1000 we set NA


# add the column to sales_df using findInterval
sales_df$buyer_fee <- consecFees$fees[findInterval(sales_df$sale_price,consecFees$ranges)]

结果 :

> sales_df
  invoice_id sale_price buyer_fee
1          1        100        25
2          2        275        50
3          3        350        75
4          4        500       125
5          5        675       125

推荐阅读