r - 如何按组将拟合值的列添加到数据框?

标签 r error-handling dplyr regression quantreg

说我有一个像这样的数据框:

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,并将fittedresid泛型方法中的值添加到数据框中?

我知道我可以做:
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个组,因此我不想只为每个组复制和粘贴代码。

我尝试将dplyrdo结合使用,但没有取得任何进展。我以为可能是这样的:
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/

相关文章:

php - 如何通过 php.ini 禁用警告和通知

r - 在R中的map()中使用管道

r - 使用正则表达式分隔列

r - 获取R包必要的外部数据的最佳方法

reactjs - BugSnag错误边界不记录错误

r - 使用R从Google Analytics API查询多个URL

php - 最大执行时间错误处理

r - 来自 dplyr 的 bind_rows() 问题 - 包加载错误?

r - 枚举一系列不同概率的伯努利试验的所有可能的组合概率

r - 无法在最新版本的 RStudio 和 R Version.3.1.1 中安装软件包