创建函数以根据摘要自动创建图(fit<-lm(y〜x1 + x2 + ... xn)) [英] Create function to automatically create plots from summary(fit <- lm( y ~ x1 + x2 +... xn))

查看:72
本文介绍了创建函数以根据摘要自动创建图(fit<-lm(y〜x1 + x2 + ... xn))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在多次使用x变量的较小变化进行相同的回归.我的目标是确定此线性回归模型的所有变量的拟合度和显着性后,才能查看所有主要图表.我不需要一个一个地创建每个图,而是要一个函数遍历下面列表中的变量(x1 ... xn).

I am running the same regression with small alterations of x variables several times. My aim is after having determined the fit and significance of each variable for this linear regression model to view all all major plots. Instead of having to create each plot one by one, I want a function to loop through my variables (x1...xn) from the following list.

fit< -lm(y〜x1 + x2 + ... xn))

fit <-lm( y ~ x1 + x2 +... xn))

我要为所有x创建的图是 1)上面函数中所有x的'x vs y' 2)'x与预测y 3)x与残差 4)x与时间的关系,其中时间不是回归中使用的变量,而是在数据来源的数据框中提供的.

The plots I want to create for all x are 1) 'x versus y' for all x in the function above 2) 'x versus predicted y 3) x versus residuals 4) x versus time, where time is not a variable used in the regression but provided in the dataframe the data comes from.

我知道如何从拟合中访问系数,但是由于名称是字符,因此我无法使用摘要中的系数名称并将其重新用于创建绘图的函数中.

I know how to access the coefficients from fit, however I am not able to use the coefficient names from the summary and reuse them in a function for creating the plots, as the names are characters.

我希望我的问题已经被清楚地描述了,还没有被问到.

I hope my question has been clearly described and hasn't been asked already.

谢谢!

推荐答案

创建一些模拟数据

dat <- data.frame(x1=rnorm(100), x2=rnorm(100,4,5), x3=rnorm(100,8,27), 
  x4=rnorm(100,-6,0.1), t=(1:100)+runif(100,-2,2))
dat <- transform(dat, y=x1+4*x2+3.6*x3+4.7*x4+rnorm(100,3,50))

健身

fit <- lm(y~x1+x2+x3+x4, data=dat)

计算预测值

dat$yhat <- predict(fit)

计算残差

dat$resid <- residuals(fit)

获取变量名的向量

vars <- names(coef(fit))[-1]

如果使用名称的此字符表示来构建公式的字符串版本并进行翻译,则可以使用该名称的字符表示来绘制图表.下面是这四个图,它们被包裹在所有变量上的循环中.此外,将ask设置为TRUE可以将其包围起来,以便您有机会查看每个图.或者,您可以在屏幕上排列多个图,或将它们全部写入文件中以供以后查看.

A plot can be made using this character representation of the name if you use it to build a string version of a formula and translate that. The four plots are below, and the are wrapped in a loop over all the vars. Additionally, this is surrounded by setting ask to TRUE so that you get a chance to see each plot. Alternatively you arrange multiple plots on the screen, or write them all to files to review later.

opar <- par(ask=TRUE)
for (v in vars) {
  plot(as.formula(paste("y~",v)), data=dat)
  plot(as.formula(paste("yhat~",v)), data=dat)
  plot(as.formula(paste("resid~",v)), data=dat)
  plot(as.formula(paste("t~",v)), data=dat)
}
par(opar)

这篇关于创建函数以根据摘要自动创建图(fit&lt;-lm(y〜x1 + x2 + ... xn))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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