R直接在可能性()命令或tryCatch中使用函数

时间:2018-08-31 16:50:09

标签: r try-catch tidyverse purrr

我正在使用map,并想使用possibly或(tryCatch)捕获错误,并用NA替换。如果我先明确指定该函数,然后传递给possibly,则可以使其正常工作,但是如果我在一行中执行该操作,则无法使其正常工作。

library(dplyr)
library(tidyverse)
#set up data
df <- data.frame (id=rep(1:10,each=10),
                  s1=rnorm(100, 10, 2),
                  d2=rnorm(100, 5, 2),
                  drugA=rbinom(100,1,0.5)) 
#values
values <- c(.3, .2, 0)
#set up function
out <- map(values, ~df %>% 
             group_by(id) %>% 
             mutate(intpsi = (s1-d2)*exp(drugA*.x))) %>% 
  map( ~glm(as.factor(drugA) ~ s1 + d2 + intpsi, .x, family=quasibinomial,maxit=1000))

现在,如果我想从out列表中提取系数,则可以执行以下操作:

    #separately specify function
    fg <- function(x) {sprintf(" %.2f", summary(x)$coefficients["intpsi",3])}
    #use function with possibly
    out1<-map(out,~possibly(fg,NA_real_)(.x))

    #works! 
    out1
    [[1]]
    [1] " 4.72"

    [[2]]
    [1] " 4.72"

    [[3]]
    [1] NA

如果我在一行中尝试这最后一点,将不起作用:

out2<-map(out, ~possibly(sprintf(" %.2f ", summary(.x)$coefficients["intpsi",3]), NA_real_)(.x))

Error in summary(.x)$coefficients["intpsi", 3] : subscript out of bounds

这也不是:

out1<-map(out, ~(possibly(function() {sprintf(" %.2f", summary(.x)$coefficients["intpsi",3])}, NA_real_)(.x)))
R>out1
[[1]]
[1] NA

[[2]]
[1] NA

[[3]]
[1] NA

我认为它做的很小,我做错了吗?希望看到tryCatch解决方案,也许在这里会更好?

0 个答案:

没有答案