累积曲线上点的R插值

时间:2016-12-02 12:13:22

标签: r interpolation

我对不同比例的人口(涵盖百分比)有以下累积成本数据(十亿美元):

test_df <- data.frame(cum.pop = c(0, 8.3, 37.7, 70.5, 90.5, 96.7, 98.7, 100),
                  cum.cost = c(0, 0.7, 3.4, 6.3, 14.1, 22.6, 28.3, 41.9))

我想计算每20亿美元覆盖的人口百分比。

编辑:

线性拟合不会产生所需的结果,因为曲线是指数的,如下图所示: enter image description here

我如何拟合指数? AEBilgrau使用Approxfun的答案,但输出结果不准确。

2 个答案:

答案 0 :(得分:1)

您也可以尝试拟合样条曲线(尽管存在过度拟合的风险):

library(spline)
ispl <- interpSpline(cum.pop ~ cum.cost,  test_df)

# plots the interpolated spline
plot(ispl)    
points(test_df[,2], test_df[,1], pch=19)

enter image description here

cum.cost <- seq(0, 42, 2) # every 2B$
cum.cost
# [1]  0  2  4  6  8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42
# predicted pop
pred.cum.pop <- predict(ispl, cum.cost)$y
pred.cum.pop
# [1]   0.00000  22.51128  44.72944  67.60543  82.57553  89.24549  90.81892  90.50744  90.98837  92.45519  94.38025  96.23579  97.53846  98.26304  98.65462
#[16]  98.93703  99.17804  99.38472  99.56401  99.72285  99.86816 100.00689

# plots othe predicted cum.pop for each 2B$ rise in cum.cost
plot(ispl)    
points(cum.cost, pred.cum.pop, col='red', pch=19)

enter image description here

答案 1 :(得分:0)

没有“最佳方法”这样的东西 - 至少在你没有用“最佳”指明你的意思并且提供的信息很少时也是如此。当然,有些方法比其他方法更好。 无论如何,我想这不是一个真正的编程问题。因此,您需要确定哪种方法符合您的要求并希望您想做。

如果你想做简单的线性插值(可能会或可能不适合你的目的),你可以做这样的事情

 # Load your toy data
 test_df <- data.frame(cum.pop = c(0, 8.3, 37.7, 70.5, 90.5, 96.7, 98.7, 100),
                      cum.cost = c(0, 0.7, 3.4, 6.3, 14.1, 22.6, 28.3, 41.9))

# Create a function that carries out the interpolation
get_pop <- approxfun(x = test_df$cum.cost, y = test_df$cum.pop)

# Call the function for every two billion dollars
get_pop(seq(0, 40, by = 2))

这是读取情节的对应

 plot(cum.pop ~ cum.cost, data = test_df, type = "b")

从表面上看,这里的数据似乎相对较少。所以这可能就好了。