4

假设我们有一个f1适合某些数据点x的线性模型:y

f1 <- lm(y ~ x,data=d)

如何使用R中的这种拟合在yx值(与旧x值不同但在旧值范围内)生成新值?xf1

4

3 回答 3

2

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")

在此处输入图像描述

(黑色为原始数据,红色为模拟数据)

于 2020-02-03T14:18:32.157 回答
1

我正在研究同样的问题。

简单来说,可以通过使用残差中的样本来完成:

mod <- lm(y ~ x, data = df)

x_new <- c(5) # value that you need to simulate for.
pred <- predict(mod, newdata=data.frame(x = x_new))
err <- sample(mod$residuals, 1)
y <- pred + err

有一个simulate(fit, nsim = 10, XX = x_new)功能,应该为你做。

于 2016-05-10T15:59:54.093 回答
0

您可以predict为此使用:

x <- runif(20, 0, 100)
y <- 5*x + rnorm(20, 0, 10)
df <- data.frame(x, y)
df
plot(df)

mod <- lm(y ~ x, data = df)

x_new <- 1:100
pred <- predict(mod, newdata=data.frame(x = x_new))
plot(df)
points(x_new, pred)
于 2013-04-08T21:41:26.160 回答