here is the 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))
Notice what v3NA contains, so when I try to set 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
How can I catch this error and replace it with the default value if only NSs exist.
Please note that it may also happen that v4NA has, and if v3 = c (1, NA) and v4 = c (NA, 2), he also could not build a linear model.
For example, if it dfdoes not contain any "c", then I can easily do it with
if(nrow(slope) == 0) slope <- 0
because then the slope is an empty data frame.