说我有一个像这样的数据框:
X <- data_frame(
x = rep(seq(from = 1, to = 10, by = 1), 3),
y = 2*x + rnorm(length(x), sd = 0.5),
g = rep(LETTERS[1:3], each = length(x)/3))
如何拟合由变量
y~x
分组的回归g
,并将fitted
和resid
泛型方法中的值添加到数据框中?我知道我可以做:
A <- X[X$g == "A",]
mA <- with(A, lm(y ~ x))
A$fit <- fitted(mA)
A$res <- resid(mA)
B <- X[X$g == "B",]
mB <- with(B, lm(y ~ x))
B$fit <- fitted(mB)
B$res <- resid(mB)
C <- X[X$g == "C",]
mC <- with(B, lm(y ~ x))
C$fit <- fitted(mC)
C$res <- resid(mC)
然后
rbind(A, B, C)
。但是,在现实生活中,我没有使用lm
(我在rqss
包中使用了quantreg
)。该方法有时会失败,因此我需要进行错误处理,在这里我想将NA
放到所有失败的行中。另外,有超过3个组,因此我不想只为每个组复制和粘贴代码。我尝试将
dplyr
与do
结合使用,但没有取得任何进展。我以为可能是这样的:make_qfits <- function(data) {
data %>%
group_by(g) %>%
do(failwith(NULL, rqss), formula = y ~ qss(x, lambda = 3))
}
用这种方法容易做到吗? R基中还有另一种方法吗?
最佳答案
对于lm
模型,您可以尝试
library(nlme) # lmList to do lm by group
library(ggplot2) # fortify to get out the fitted/resid data
do.call(rbind, lapply(lmList(y ~ x | g, data=X), fortify))
这会在“.resid”和“.fitted”列中为您提供残差和拟合数据,以及一堆其他拟合数据。默认情况下,行名将以
g
的字母为前缀。使用
rqss
模型可能会失败do.call(rbind, lapply(split(X, X$g), function(z) {
fit <- tryCatch({
rqss(y ~ x, data=z)
}, error=function(e) NULL)
if (is.null(fit)) data.frame(resid=numeric(0), fitted=numeric(0))
else data.frame(resid=fit$resid, fitted=fitted(fit))
}))
关于r - 如何按组将拟合值的列添加到数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31734722/