是否有一个函数或程序包可以模拟从lm()返回的对象的预测? [英] Is there a function or package which will simulate predictions for an object returned from lm()?

查看:134
本文介绍了是否有一个函数或程序包可以模拟从lm()返回的对象的预测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个类似于"runif","rnorm"之类的函数,可以为线性模型生成模拟预测?我可以自己编写代码,但是代码很丑陋,我认为这是某人以前做过的事情.

Is there a single function, similar to "runif", "rnorm" and the like which will produce simulated predictions for a linear model? I can code it on my own, but the code is ugly and I assume that this is something someone has done before.

slope = 1.5
intercept = 0
x = as.numeric(1:10)
e = rnorm(10, mean=0, sd = 1)
y = slope * x + intercept + e
fit = lm(y ~ x, data = df)
newX = data.frame(x = as.numeric(11:15))

我感兴趣的是一个看起来像下面的行的函数:

What I'm interested in is a function that looks like the line below:

sims = rlm(1000, fit, newX)

该函数将基于新的x变量返回y个值的1000个模拟.

That function would return 1000 simulations of y values, based on the new x variables.

推荐答案

表明加文·辛普森(Gavin Simpson)修改stats:::simulate.lm的建议是可行的.

Showing that Gavin Simpson's suggestion of modifying stats:::simulate.lm is a viable one.

## Modify stats:::simulate.lm by inserting some tracing code immediately
## following the line that reads "ftd <- fitted(object)" 
trace(what = stats:::simulate.lm,
      tracer = quote(ftd <- list(...)[["XX"]]),
      at = list(5))

## Prepare the data and 'fit' object 
df <- data.frame(x=x<-1:10, y=1.5*x + rnorm(length(x)))
fit <- lm(y ~ x, data = df)
newX <- 8:1

## Pass in new x-values via the argument 'XX'
simulate(fit, nsim = 4, XX = newX)
#      sim_1    sim_2     sim_3    sim_4
# 1 8.047710 8.647585 7.9798728 8.400672
# 2 6.398029 7.714972 7.9713929 7.813381
# 3 5.469346 5.626544 4.8691962 5.282176
# 4 4.689371 4.310656 4.2029540 5.257732
# 5 4.628518 4.467887 3.6893648 4.018744
# 6 2.724857 4.280262 2.8902676 4.347371
# 7 1.532617 2.400321 2.4991168 3.357327
# 8 1.300993 1.379705 0.1740421 1.549881

可行,但这是一种更清洁(并且可能更好)的方法:

That works, but this is a cleaner (and likely better) approach:

## A function for simulating at new x-values
simulateX <- function(object, nsim=1, seed=NULL, X, ...) {
    object$fitted.values <- X
    simulate(object=object, nsim=nsim, seed=seed, ...)
}

## Prepare a fit object and some new x-values
df <- data.frame(x=x<-1:10, y=1.5*x + rnorm(length(x)))
fit <- lm(y ~ x, data = df)    
newX <- 8:1

## Try it out
simulateX(fit,  nsim = 4, X = newX)
#      sim_1    sim_2     sim_3      sim_4
# 1 8.828988 6.890874  7.397280  8.1605794
# 2 6.162839 8.174032  3.612395  7.7999466
# 3 5.861858 6.351116  3.448205  4.3721326
# 4 5.298132 4.448778  2.006416  5.7637724
# 5 7.260219 4.015543  3.063622  4.2845775
# 6 3.107047 4.859839  6.202650 -1.0956775
# 7 1.501132 1.086691 -1.273628  0.4926548
# 8 1.197866 1.573567  2.137449  0.9694006

这篇关于是否有一个函数或程序包可以模拟从lm()返回的对象的预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆