f1假设我们有一个适合某些x数据点的线性模型y:
f1 <- lm(y ~ x,data=d)
Run Code Online (Sandbox Code Playgroud)
如何使用R中的这种拟合y以新x值(与旧值不同x但在旧值范围内x)生成新值?f1
stats:::simulate.lm允许您从装有 的线性模型中采样lm。(与@Bulat 的方法相反,它使用残差方差的无偏估计)。要模拟自变量的不同值,您可以像这样进行修改:
# simulate example data
x <- runif(20, 0, 100)
y <- 5*x + rnorm(20, 0, 10)
df <- data.frame(x, y)
# fit linear model
mod <- lm(y ~ x, data = df)
# new values of the independent variable
x_new <- 1:100
# replaces fitted values of the model object with predictions for new data,
mod$fitted.values <- predict(mod, data.frame(x=x_new)) # "hack"
# simulate samples appropriate noise and adds it the models `fitted.values`
y_new <- simulate(mod)[, 1] # simulate can return multiple samples (as columns), we only need one
# visualize original data ...
plot(df)
# ... alongside simulated data at new values of the independent variable (x)
points(x_new, y_new, col="red")
Run Code Online (Sandbox Code Playgroud)
(原始数据为黑色,模拟数据为红色)