首页 > 解决方案 > R中多个分组的线性插值

问题描述

我有以下数据集:

                 District      Type   DaysBtwn Start_Day  End_Day Start_Vol   End_Vol 
1             A             0             3             0             31             28             23 
2             A             1             3             0             31             24             0 
3             B             0             3             0             31             17700     10526 
4             B             1             3             0             31             44000       35800 
5             C             0             3             0             31             5700         0 
6             C             1             3             0             31             35000       500

对于每个组组合District & Type,我想做一个简单的线性插值:for a x=Days (Start_Day and End_Day)并且y=Volumes (Start_Vol and End_Vol),我想要为 xout=DaysBtwn 返回的估计音量。

我已经尝试了很多东西。我认为我的数据设置方式存在问题。有人可以为我指出正确的方向,以了解如何使用 R 中的 approx 函数来获得所需的输出吗?我不介意移动我的数据集以获得大约的正确格式。

所需输出的示例:

District Type EstimatedVol 
1           0           25 
2           1           15 
3           0           13000 
4           1           39000 
5           0           2500 
6           1           25000
   dt <- data.table(input) interpolation <- dt[, approx(x,y,xout=z), by=list(input$District,input$Type)]

标签: rlinear-interpolation

解决方案


为什么不直接计算呢?

dt$EstimatedVol <- (End_Vol - Start_Vol) / (End_Day - Start_Day) * (DaysBtwn - Start_Day) + Start_Vol

推荐阅读