How to add all variables its second degree in lm()? [duplicate]

柔情痞子 提交于 2019-12-04 06:04:24

问题


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)

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?


回答1:


When assuming the first variable in data is our 'y', we get this:

as.formula(
    paste('y ~',paste('poly(',colnames(data[-1]),',2)',collapse = ' + ')
)


来源:https://stackoverflow.com/questions/39821262/how-to-add-all-variables-its-second-degree-in-lm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!