如何在lm()中将所有变量的第二级相加? [英] How to add all variables its second degree in lm()?
本文介绍了如何在lm()中将所有变量的第二级相加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有16个变量的数据框.当我进行多元线性回归时,请执行以下操作:
I have a dataframe with 16 variables. When I do multiple linear regression I do the following:
fit <- lm(y ~ .,data=data)
现在,我知道如何添加其中一个变量的第二度项:
Now, I know how to add a second degree term of one of the variables:
fit2 <- lm(y ~ poly(x1,2) + .,data=data)
但是现在我不想将所有16个变量都写出来.如何为所有变量轻松地做到这一点?
But now I don't want to write this out for all of my 16 variables. How can I do this in an easy way for all my variables?
推荐答案
当假设数据中的第一个变量是我们的'y'时,我们得到:
When assuming the first variable in data is our 'y', we get this:
as.formula(
paste('y ~',paste('poly(',colnames(data[-1]),',2)',collapse = ' + ')
)
这篇关于如何在lm()中将所有变量的第二级相加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文