用R中的lowess方法计算加权平均值

时间:2013-02-04 14:18:17

标签: r smooth

我试图使用R中的lowess方法来计算沿x轴不均匀分布的数据集的加权平均值。例如,前5个数据点是这样的,其中第一列是x,第二列是y。

  

375.0 2040.0
     472.0 5538.0
     510.0 4488.0
     573.0 2668.0
     586.0 7664.0

我在R中使用了以下命令:

x<-read.table(add,header=FALSE,sep="\t")
y<-lowess(x[,1],x[,2],f=0.01)
write.table(y, file = results , sep = "\t", col.names =FALSE, row.names =FALSE)

输出如下:

enter image description here

绿线表示平滑函数在matlab(三立方核)中计算的平均值,红线表示由R中的lowess方法计算的平均线。蓝点是数据点。  我找不到为什么R中的方法不起作用。你有什么想法吗?

以下是link部分数据。

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

matlab中的smooth函数就像一个过滤器,

yy = smooth(y)
yy(1) = y(1)
yy(2) = (y(1) + y(2) + y(3))/3
yy(3) = (y(1) + y(2) + y(3) + y(4) + y(5))/5  ## convolution of size 5
yy(4) = (y(2) + y(3) + y(4) + y(5) + y(6))/5

我认为最好在这里做一个简单的顺利。

此处尝试使用黄土 lowesss ,f = 0.2(1/5)并使用 smooth.spline

我正在使用ggplot2进行绘图(使用带有某些alpha的geom_jitter)

library(ggplot2)
dat <-  subset(data, V2 < 5000)
#dat <-  data
xy <- lowess(dat$V1,dat$V2,f = 0.8)
xy <- as.data.frame(do.call(cbind,xy))

p1<- ggplot(data = dat, aes(x= V1, y = V2))+
  geom_jitter(position = position_jitter(width = .2), alpha= 0.1)+
  geom_smooth()

xy <- lowess(dat$V1,dat$V2,f = 0.2)
xy <- as.data.frame(do.call(cbind,xy))
xy.smooth <- smooth.spline(dat$V1,dat$V2)
xy.smooth <- data.frame(x= xy.smooth$x,y = xy.smooth$y)

p2 <- ggplot(data = dat, aes(x= V1, y = V2))+  
  geom_jitter(position = position_jitter(width = .2), alpha= 0.1)+
  geom_line(data = xy, aes(x=x, y = y, group = 1 ), color = 'red')+
  geom_line(data = xy.smooth, aes(x=x, y = y, group = 1 ), color = 'blue')

library(gridExtra)               
grid.arrange(p1,p2) 

enter image description here