问题
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