【问题标题】:why does my function work on it's own but not with sapply?为什么我的功能可以自己工作,但不能与 sapply 一起工作?
【发布时间】:2021-05-25 19:44:34
【问题描述】:

我正在从事一个 COVID 分析项目。我有每个州的数据框列表“sc”,每个数据框都包含该州的日期和事件案例列:

sc$Alabama
# A tibble: 489 x 3
# Groups:   state [1]
   state   date       incident_cases
   <chr>   <chr>               <dbl>
 1 Alabama 2020-01-22              0
 2 Alabama 2020-01-23              0
 3 Alabama 2020-01-24              0
 4 Alabama 2020-01-25              0
 5 Alabama 2020-01-26              0

我已经定义了一个函数来给我 COVID 的再生数:

get_r<-function(df){
as.incidence(df$incident_cases,df$date) %>% 
estimate_R(method = 'parametric_si', config=make_config(list(mean_si=5.6,std_si=4.2)))
}

这个函数在我的列表'sc'的单个元素上完美运行

get_r(sc$Alabama) 

但是,当我使用 sapply 在每个状态下运行该函数时,都会出现以下错误

sapply(sc,get_r)
Default config will estimate R on weekly sliding windows.
    To change this change the t_start and t_end arguments. 
Default config will estimate R on weekly sliding windows.
    To change this change the t_start and t_end arguments. 
 Error: At least one (non-NA) date must be provided 

我尝试将日期列重新格式化为日期,但这并没有改变任何内容。非常感谢您对我收到此错误的原因以及如何解决它的任何想法。

【问题讨论】:

  • 你们的一个州没有日期 - NA。试试:sapply(sc, function(i) table(is.na(i[, "date"]))) 看看是否所有州都有非 na 日期。
  • 谢谢你。当我运行这个时,所有状态都返回 FALSE,我相信这意味着没有丢失的日期。我还用 sum(is.na()) 对每个状态进行了检查,结果为 0
  • 那么我的猜测是:某处代码试图将其转换为日期,但失败了,所以你得到了 NA。

标签: r bioinformatics


【解决方案1】:

这不是一个答案,我只是无法将此建议放入评论中。

尝试以下方法:

get_r <- function(df){
tryCatch({
  as.incidence(df$incident_cases,df$date) %>% 
    estimate_R(method = 'parametric_si', 
               config=make_config(list(mean_si=5.6,std_si=4.2)))
}, error = function(e) NA)

}

这样,所有错误都将变成 NA,您希望能够找到哪些状态是问题

results <- lapply(sc, get_r)
vapply(results, identical, FUN.VALUE = logical(1), y = NA) %>%
  which()

如果没有可重现的示例,我们可能无法确定确切的问题是什么,但这至少应该可以帮助您开始调试数据。

【讨论】:

    猜你喜欢
    • 2020-03-12
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2010-10-28
    • 2021-04-29
    • 2015-03-16
    • 1970-01-01
    相关资源
    最近更新 更多