使用线性模型捕获NAs [英] catch NAs using linear model with dplyr
问题描述
这里是一个例外的数据框架
here's an exmaple data frame
library(dplyr)
df <- data.frame(id=c(1,1,1,2,2,2),
v2=factor(c("a","c","c","a","b","d")),
v3=c(1,NA,NA,6,7,9),
v4=c(5:10))
请注意, v3
包含NAs,所以当我尝试为每个 id
,我收到一个错误:
Note that v3
contains NAs, so when I try to fit a linear model for each id
, I get an error:
slope <- df %>% filter(v2=="c") %>%
group_by(id) %>%
do(fit = lm(v3 ~ v4, .)) %>%
summarise(slope = coef(fit)[2])
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) :
0 (non-NA) cases
如果只有NAs,我如何捕获此错误并将其替换为默认值
How can I catch this error and replace it with a default value if only NAs exist.
请注意,也可能发生 v4
有NAs,如果v3 = c(1,NA )和
v4 = c(NA,2)它也不能构建线性模型。
Note that it could also happen that v4
has NAs, and if v3=c(1,NA) and
v4=c(NA,2) it could not build a linear model as well.
例如,如果 df
不包含任何c然后我可以轻松地这样做
For example, if df
does not contain any "c" then I can do this easily with
if(nrow(slope) == 0) slope <- 0
因为这个斜率是一个空数据框。
because then slope is an empty data frame.
推荐答案
我们可以在 do
中使用 if / else
检查 NA
元素。如果全部
元素在'v3'或( | $ c)中
NA
$ c>)'v4',它应该返回斜率为NA或 else
执行 lm
并获得斜率价值。
We could use an if/else
condition within do
to check the NA
elements. If all
the elements are NA
in either 'v3' or (|
) 'v4', it should return the slope as NA or else
do the lm
and get the slope value.
df %>%
filter(v2=='c') %>%
group_by(id) %>%
do({if(all(is.na(.$v3))|all(is.na(.$v4)))
data.frame(slope=NA)
else data.frame(slope=coef(lm(v3~v4, .))[2])}) %>%
slice(1L) %>%
ungroup() %>%
select(-id)
data
data
df <- data.frame(id=c(1,1,1,2,2,2, 3, 3, 3,3, 3, 4, 4),
v2=factor(c("a","c","c","a","b","d", "c", "c", "a", "c", "c", "c", "c")),
v3=c(1,NA,NA,6,7,9, NA, 1, NA, 5,8, NA, 5 ),
v4=c(5:17))
这篇关于使用线性模型捕获NAs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!