Reputation: 511
I have a code that tries to smooth input data. It works but it's crude. Is there a better way of doing it?
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)
Having to plot g
is not the best way of doing things. Is there a way to suppress this?
Upvotes: 0
Views: 66
Reputation: 1200
you are passing an argument, but you are not using it in the body of the function. I suggest also to parametrise your arguments to achieve greater flexibility
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]])
Upvotes: 0
Reputation: 1064
You can use the same formula you used in ggplot without ggplot:
fitted <- lm(df[,2] ~ poly(df[,1],21))
plot(x,y)
lines(x,fitted$fitted.values, col="blue", ldw=4)
Upvotes: 1