我想使用由软件包tsreg
的函数WRS
定义的非参数模型,并通过ggplot
将其绘制在geom_smooth
上。问题是geom_smooth
函数需要参数formula
,data
和weights
,但是tsreg
函数没有参数。为了解决这个问题,我构建了一个返回模型的函数,然后在method
参数中使用了该模型,但是这样做不会显示geom_smooth。谁能帮助我解决这个问题?
我在下面编写代码以帮助您理解我的问题:
# first: install dependent packages
install.packages(c("MASS", "akima", "robustbase"))
# second: install suggested packages
install.packages(c("cobs", "robust", "mgcv", "scatterplot3d", "quantreg",
"rrcov", "lars", "pwr", "trimcluster", "parallel", "mc2d", "psych", "Rfit"))
# third: install WRS (Wilcox Robust Statistics)
install.packages("WRS", repos="http://R-Forge.R-project.org", type="source")
require(WRS)
linear_regresion_non_parametric <- function(formula, data, weights) {
reg <- WRS::tsreg(x = data$var1.name, y = data$var2.name)
n <- reg$n
n.keep <- reg$n.keep
Intercept <- reg$coef[1]
Slope <- reg$coef[2]
res <- reg$residuals
stregnth <- reg$Strength.Assoc
potencia <- reg$Explanatory.Power
model <- list(x = data$var1.name, y = Intercept +
Slope*data$var1.name)
class(model) <- "my_smooth"
return(model)
}
predictdf.my_smooth <- function(model, xsep, se, level) {
data.frame(x = model$x, y = model$pred)
}
ggplot(data.frame.name, aes(y = var2.name,x = var1.name)) +
geom_smooth(method = "linear_regresion_non_parametric", method.args =
list(data = dadesi),
se=FALSE, show.legend = TRUE) +
geom_point() +
labs(x = "X (%)", y = "Y")+
ggtitle(paste("Regresión Lineal no paramétrica"))