gpt4 book ai didi

r - 跟踪 dplyr 链中哪个组失败

转载 作者:行者123 更新时间:2023-12-04 17:44:06 25 4
gpt4 key购买 nike

使用 group_by 时如何找出哪个组失败了在 dplyr类型链。举个例子:

library(dplyr)

data(iris)

iris %>%
group_by(Species) %>%
do(mod=lm(Petal.Length ~ Petal.Width, data = .)) %>%
mutate(Slope = summary(mod)$coeff[2])

工作正常。现在,如果我将一些问题数据添加到 iris :
iris$Petal.Width[iris$Species=="versicolor"]= NA

这样在尝试运行线性模型时失败:
iris_sub <- iris[iris$Species=="versicolor",]
lm(Petal.Length ~ Petal.Width, data = iris_sub)

但是,如果我运行这个,我正在用大量数据集接近这个盲点:
iris %>%
group_by(Species) %>%
do(mod=lm(Petal.Length ~ Petal.Width, data = .)) %>%
mutate(Slope = summary(mod)$coeff[2])

此错误消息无法帮助我找到模型失败的级别:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases



我可以使用如下所示的循环。这至少让我知道 Species 的级别功能失败。但是,我更喜欢使用 dplyr 设置:
lmdf <- c()
for (i in unique(iris$Species)) {
cat(i, "\n")
u <- iris %>%
filter(Species==i) %>%
do(mod=lm(Petal.Length ~ Petal.Width, data = .))
lmdf = rbind(lmdf, u)
}

关于实现这一目标的更好方法的任何建议?总而言之,我正在尝试使用 dplyr类型框架以确定功能在哪个组级别失败。
tryCatch引用解决方案 here似乎不再起作用。我收到此错误:

Error in tryCatch(lm(v3 ~ v4, df), error = if (e$message == all_na_msg) default else stop(e)) : object 'e' not found

最佳答案

使用 purrr::safely 的完整示例:
准备

library(tidyverse)
data(iris)
iris$Petal.Width[iris$Species == "versicolor"] <- NA
安全运行模型
如果您对实际错误不感兴趣(即原因是 0 (non-NA) cases ),您可以执行以下操作:
iris %>%
group_by(Species) %>%
do(mod = safely(lm)(Petal.Length ~ Petal.Width, data = .)$result) %>%
mutate(Slope = ifelse(!is.null(mod), summary(mod)$coeff[2], NA))
我们完成了!
Source: local data frame [3 x 3]
Groups: <by row>

# A tibble: 3 × 3
Species mod Slope
<fctr> <list> <dbl>
1 setosa <S3: lm> 0.5464903
2 versicolor <NULL> NA
3 virginica <S3: lm> 0.6472593
我们可以清楚地看到哪个组失败了(因为它有 NULL 而不是模型,而它的 Slope 是未知的)。此外,我们仍然为其他组获得了正确的模型和斜率,因此我们没有浪费计算时间(在更大的数据集上运行复杂模型时,这可能非常好)。
跟踪模型和错误
step1 <- iris %>%
group_by(Species) %>%
do(res = safely(lm)(Petal.Length ~ Petal.Width, data = .)) %>%
mutate(err = map(list(res), 'error'),
mod = map(list(res), 'result'))
不幸的是,我们必须使用额外的 list在那里打电话,不完全确定为什么。或者,您可以 ungroup第一的。
要查看哪些(如果有)组出错,我们可以使用:
filter(step1, !is.null(err))
简单地拯救非错误组的结果 filter第一的:
step1 %>% 
filter(is.null(err)) %>%
mutate(Slope = summary(mod)$coeff[2])
您也可以查看 broom如果要获取 tidy 链中模型的系数,请打包。

关于r - 跟踪 dplyr 链中哪个组失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com