Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我用R写了一段代码,试图平滑输入数据。有更好的方法吗?_R - Fatal编程技术网

我用R写了一段代码,试图平滑输入数据。有更好的方法吗?

我用R写了一段代码,试图平滑输入数据。有更好的方法吗?,r,R,我有一个试图平滑输入数据的代码。它有效,但它是粗糙的。有更好的方法吗 smooth.data <- function(X){ require(ggplot2) g <- ggplot(df,aes(x=df[,1],y=df[,2])) + geom_point() g <- g + stat_smooth(aes(outfitx=fitx<<-..x.., outfit=fit<<-..y..), method = "lm", formu

我有一个试图平滑输入数据的代码。它有效,但它是粗糙的。有更好的方法吗

smooth.data <- function(X){

  require(ggplot2)
  g <- ggplot(df,aes(x=df[,1],y=df[,2])) + geom_point()
  g <- g + stat_smooth(aes(outfitx=fitx<<-..x.., outfit=fit<<-..y..), method = "lm", formula = y ~ poly(x, 21), se = FALSE)
  plot(g)
  plot(fitx, fit, type = "l")
  return(list(fitx, fit))
}

x <- seq(0.0,10,0.1)
y <- exp(-x)*sin(x/(2*pi))+runif(10/0.1+1, 0.0, 0.05)
df <- data.frame(cbind(x,y))
smooth.data.res <- smooth.data(df)  
xx <- smooth.data.res[[1]]
yy <- smooth.data.res[[2]]
plot(x,y)
lines(xx,yy, col="blue", ldw=4)

绘制g并不是做事情的最佳方式。有没有办法抑制这种情况?

您可以使用在ggplot中使用的相同公式,而不使用ggplot:

fitted <- lm(df[,2] ~ poly(df[,1],21))
plot(x,y)
lines(x,fitted$fitted.values, col="blue", ldw=4)

您正在传递一个参数,但没有在函数体中使用它。我还建议将你的论点参数化,以获得更大的灵活性

smooth.data <- function(x,y,se=FALSE,npol=21){

  require(ggplot2)
  df<-data.frame(cbind(x,y))
  g <- ggplot(df,aes(x=df[,1],y=df[,2])) + geom_point()
  g <- g + geom_smooth(aes(outfix=fitx<<-..x.., out=fit<<-..y..),method = "lm", formula = y ~ poly(x, npol=npol), se = se)
  return(list(fitx, fit,g))
}


x <- seq(0.0,10,0.1)
y <- exp(-x)*sin(x/(2*pi))+runif(10/0.1+1, 0.0, 0.05)
smooth.data.res <- smooth.data(x,y,se=TRUE,npol=21)  

plot(smooth.data.res[[3]])