将离散点转换为连续函数

时间:2019-09-19 11:55:05

标签: r

我正在寻找一种从一系列方面获得连续功能的方法。

假设我的离散点是:

df_demand <- structure(list(x = c(0, 0.2, 0.5, 0.9, 1), y = c(1, 0.5, 0.2, 
0.01, 0.01)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", 
"data.frame"))

我想创建一个连续函数,以便将y预测为特定x的函数(例如x = 0.3)。

到目前为止,我所做的是使用多项式模型来逼近此函数:

model <- glm(y ~ poly(x,3), data = df_demand)

data.frame(x = seq(0,1,length = 1000)) %>% 
  mutate(pred=predict(model, .)) %>% 
  ggplot()+
  geom_line(aes(x = x, y = pred))+
  geom_point(data = df_demand, aes(x = x, y = y), color = "red")

Polynomial model to fit discrete points

但是这种方法的问题是,根据我的输入,它不能很好地泛化。

我正在寻找一个像连续移动平均线这样的函数,我可以将其称为函数(y = moving_average(x)),但是尽管到目前为止我已经读到了什么,但我仍无法找到解决方案我的问题。

1 个答案:

答案 0 :(得分:0)

一种选择是使用splinefun

f <- splinefun(df_demand$x,df_demand$y)
plot(f)
points(df_demand$x,df_demand$y)

Spline