如何在R中建模多项式回归? [英] How to model polynomial regression in R?
问题描述
我有一个包含70个变量的数据集,我想尝试对其进行多项式回归.如果列数是三/四,我可以手动编写类似这样的代码-
I've a dataset with 70 variables, and I want to try polynomial regression on it. If the number of columns were three/four I could just hand code something like this --
model <- lm(y ~ poly(var1,3) + poly(var2,3) + poly(var4,4)
如果我们有70个变量,我们将如何处理?我们应该手动输入所有变量的名称还是有一种更简单的方法?
How would we go about this, if we have 70 variables? Should we type in manually names of all the variables or is there a easier method?
推荐答案
如果所有变量都被系统命名,则可以粘贴公式:
You could paste the formula, if all variables are named systematically:
form <- as.formula(paste("y~", paste0("poly(var", 1:10, ")", collapse="+")))
或(对于3级多项式):
or (for polynomial of 3rd degree):
form <- as.formula(paste("y~", paste0("poly(var", 1:10, ", degree=3)", collapse="+")))
此外,如果数据集中df
中只有因变量y
和相关协变量(具有非系统名称),则可以尝试
Also, if you have only the dependent variable y
and covariates of interest (that have non-systematic names) in your dataset df
, you can try
ind.y <- grep("y", colnames(df))
form <- as.formula(paste("y~", paste0("poly(", colnames(df[, -ind.y]), ", degree=3)", collapse="+")))
这篇关于如何在R中建模多项式回归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!