Catch using a linear model with dplyr

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.

+1
source share
2 answers

if/else do NA. all NA 'v3' (|) 'v4', NA else lm .

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)

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))
+2

" ", tryCatch.

, "0 (non-NA) cases", .

failwith plyr, , . .

all_na_msg <- "0 (non-NA) cases";
trymodel <- function(df, default = NA) {
  tryCatch(lm(v3 ~ v4, df),
           error = if (e$message == all_na_msg)
                     default
                   else
                     stop(e));
}

slope <- df %>% filter(v2=="c") %>% 
  group_by(id) %>% 
  do(fit = trymodel(df)) %>%
  summarise(slope = coef(fit)[2])
+1

Source: https://habr.com/ru/post/1669971/


All Articles