我多次运行相同的回归,并对 x 变量进行小幅更改。我的目标是在确定该线性回归模型的每个变量的拟合度和显着性后,查看所有主要图。我不需要一个一个地创建每个图,而是想要一个函数来循环访问以下列表中的变量 (x1...xn)。
fit <-lm( y ~ x1 + x2 +... xn))
我想为所有 x 创建的图是
1) 上面函数中所有 x 的“x 与 y”
2) 'x 与预测 y
3) x 与残差
4) x 与时间,其中时间不是回归中使用的变量,而是在数据来源的数据框中提供。
我知道如何从拟合中访问系数,但是我无法使用摘要中的系数名称并在创建绘图的函数中重用它们,因为名称是字符。
我希望我的问题已经被清楚地描述并且还没有被问过。
谢谢!
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))
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.
Thanks!
发布评论
评论(3)
创建一些模拟数据
进行拟合
计算预测值
计算残差
获取变量名称的向量
如果您使用名称的此字符表示形式构建公式的字符串版本并对其进行翻译,则可以使用该名称的字符表示来绘制绘图。下面有四个图,它们包裹在所有变量的循环中。此外,通过将
ask
设置为TRUE
来实现这一点,以便您有机会查看每个图。或者,您可以在屏幕上排列多个绘图,或者将它们全部写入文件以供稍后查看。Create some mock data
Make the fit
Compute the predicted values
Compute the residuals
Get a vector of the variable names
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
toTRUE
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.正如您所说,系数存储在拟合对象中,但是您可以通过以下方式引用它们在函数中一般访问它们:
我的猜测是,当您说您知道如何访问系数时,您是从摘要(拟合)中获取它们的这比直接从拟合中获取它们要困难一些。通过使用 fit$coeff[1] 等,您不必在函数中包含变量的名称。
The coefficients are stored in the fit objects as you say, but you can access them generically in a function by referring to them this way:
My guess is when you say you know how to access the coefficients you are getting them from summary(fit) which is a bit harder to access than taking them directly from the fit. By using fit$coeff[1] etc you don't have to have the name of the variable in your function.
直接回答我认为问题的三个选项:如何使用字符参数访问系数:
如果问题是如何绘制各种函数,那么您应该提供一个足够复杂的结构(在 R 中)以允许使用明确指定的对象集。
Three options to directly answer what I think was the question: How to access the coefficients using character arguments:
If the question was how to plot the various functions then you should supply a sufficiently complex construction (in R) to allow demonstration of methods with a well-specified set of objects.