简体   繁体   English

如何平滑R中的曲线?

[英]How to smooth a curve in R?

在此处输入图片说明

location diffrence<-c(0,0.5,1,1.5,2)
Power<-c(0,0.2,0.4,0.6,0.8,1)
plot(location diffrence,Power)

The guy which has written the paper said he has smoothed the curve using a weighted moving average with weights vector w = (0.25,0.5,0.25) but he did not explained how he did this and with which function he achieved that.i am really confused写这篇论文的人说他已经使用权重向量 w = (0.25,0.5,0.25) 的加权移动平均线平滑了曲线,但他没有解释他是如何做到这一点的,以及他用哪个函数实现了那个。我真的使困惑

Up front, as @MartinWettstein cautions, be careful in when you smooth data and what you do with it (infer from it).在前面,正如@MartinWettstein 所警告的那样,在平滑数据时要小心以及如何处理数据(从中推断)。 Having said that, a simple exponential moving average might look like this.话虽如此,一个简单的指数移动平均线可能看起来像这样。

# replacement data
x <- seq(0, 2, len=5)
y <- c(0, 0.02, 0.65, 1, 1)

# smoothed
ysm <- 
  zoo::rollapply(c(NA, y, NA), 3,
                 function(a) Hmisc::wtd.mean(a, c(0.25, 0.5, 0.25), na.rm = TRUE),
                 partial = FALSE)

# plot
plot(x, y, type = "b", pch = 16)
lines(x, ysm, col = "red")

带有平滑线的线图

Notes:笔记:

  • the zoo:: package provides a rolling window (3-wide here), calling the function once for indices 1-3, then again for indices 2-4, then 3-5, 4-6, etc. zoo::包提供了一个滚动窗口(此处为 3 宽),为索引 1-3 调用该函数一次,然后为索引 2-4、3-5、4-6 等再次调用该函数。
  • with rolling-window operations, realize that they can be center-aligned (default of zoo::rollapply ) or left/right aligned.使用滚动窗口操作,实现它们可以居中对齐( zoo::rollapply默认值)或左/右对齐。 There are some good explanations here: How to calculate 7-day moving average in R?这里有一些很好的解释:如何在 R 中计算 7 天移动平均线? ) )
  • I surround the y data with NA s so that I can mimic a partial window.我用NA包围y数据,以便我可以模拟partial窗口。 Normally with rolling-window ops, if k=3 , then the resulting vector is length(y) - (k-1) long.通常使用滚动窗口操作,如果k=3 ,则结果向量为length(y) - (k-1)长。 I'm inferring that you want to include data on the ends, so the first smoothed data point would be effectively (0.5*0 + 0.25*0.02)/0.75 , the second smoothed data point (0.25*0 + 0.5*0.02 + 0.25*0.65)/1 , and the last smoothed data point (0.25*1 + 0.5*1)/0.75 .我推断您想在末端包含数据,因此第一个平滑数据点将有效(0.5*0 + 0.25*0.02)/0.75 ,第二个平滑数据点(0.25*0 + 0.5*0.02 + 0.25*0.65)/1 ,以及最后一个平滑的数据点(0.25*1 + 0.5*1)/0.75 That is, omitting the 0.25 times a missing data point.也就是说,省略了0.25倍的缺失数据点。 That's a guess and can easily be adjusted based on your real needs.这是一个猜测,可以根据您的实际需求轻松调整。
  • I'm using Hmisc::wtd.mean , though it is trivial to write this weighted-mean function yourself.我正在使用Hmisc::wtd.mean ,尽管自己编写这个加权平均函数很简单。

This is suggestive only, and not meant to be authoritative.这只是暗示性的,并不意味着具有权威性。 Just to help you begin exploring your smoothing processes.只是为了帮助您开始探索平滑过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM