您可能想要的是排除关于最高多项式的任何内容p <= .7
(应该保留较低的度数)。假设您知道自己在做什么,您可以编写一个函数degAna()
来分析每个多项式的次数,并将其应用于由 获得的系数矩阵summary
。
REG19 <- lm(R10 ~ poly(M1, 3) + poly(M2, 3) + poly(M3, 3) + poly(M4, 3) +
poly(M5, 3) + poly(M6, 3) + poly(M7, 3) + poly(M8, 3) +
poly(M9, 3) + poly(M10, 3), WorkData)
rr <- summary(REG19)$coefficients
用 检测最高程度的函数p <= .7
:
degAna <- function(d) {
out <- as.matrix(rr[grep(paste0(")", d), rownames(rr)), "Pr(>|t|)"] <= .7)
dimnames(out) <- list(c(gsub("^.*\\((.*)\\,.+", "\\1", rownames(out))), d)
return(out)
}
lapply
degAna
到系数矩阵:
dM <- do.call(cbind, lapply(1:3, degAna)) # max. degree always 3 as in example
# 1 2 3
# M1 TRUE TRUE TRUE
# M2 TRUE TRUE TRUE
# M3 FALSE TRUE TRUE
# M4 TRUE TRUE TRUE
# M5 TRUE TRUE TRUE
# M6 TRUE FALSE TRUE
# M7 TRUE FALSE FALSE
# M8 TRUE TRUE TRUE
# M9 TRUE TRUE FALSE
# M10 TRUE FALSE TRUE
现在我们需要多项式的最后一个次数,其中p <= .7
:
tM <- apply(dM, 1, function(x) max(which(x != 0)))
tM <- tM[tM > 0] # excludes polynomes where every p < .7
# M1 M2 M3 M4 M5 M6 M7 M8 M9 M10
# 3 3 3 3 3 3 1 3 2 3
(请注意,如果多项式完全具有,即行完全是,apply
则将引发警告。由于我们在下一行将它们扔掉,我们可以忽略警告。)p <= .7
FALSE
apply(dM, 1, function(x) suppressWarnings(max(which(x != 0))))
有了这些信息,我们可以拼凑出一个新的公式reformulate
,
terms.new <- paste0("poly(", names(tM), ", ", tM, ")")
FO <- reformulate(terms.new, response="R10")
# R10 ~ poly(M1, 3) + poly(M2, 3) + poly(M3, 3) + poly(M4, 3) +
# poly(M5, 3) + poly(M6, 3) + poly(M7, 1) + poly(M8, 3) + poly(M9,
# 2) + poly(M10, 3)
有了它,我们最终可以进行所需的缩短回归。
REG19.2 <- lm(FO, WorkData)
n <- length(resid(REG19.2))
REG20.2 <- step(REG19.2, direction="backward", k=log(n))
# [...]
模拟数据
set.seed(42)
M1 <- rnorm(1e3)
M2 <- rnorm(1e3)
M3 <- rnorm(1e3)
M4 <- rnorm(1e3)
M5 <- rnorm(1e3)
M6 <- rnorm(1e3)
M7 <- rnorm(1e3)
M8 <- rnorm(1e3)
M9 <- rnorm(1e3)
M10 <- rnorm(1e3)
R10 <- 6 + 5*M1^3 + 4.5*M2^3 + 4*M3^2 + 3.5*M4 + 3*M5 + 2.5*M6 + 2*M7 +
.5*rnorm(1e3, 1, sd=20)
WorkData <- data.frame(M1, M2, M3, M4, M5, M6, M7, M8, M9, M10, R10)