进度条和映射(输入为列表)

Progress bar and mapply (input as list)

我想监控我的 mapply 函数的进度。数据由 2 个列表组成,并且有一个带有 2 个参数的函数。

如果我对接受 1 个参数的函数做类似的事情,我可以使用 ldply 而不是 lapply。 (我想 rbind.fill 输出到 data.frame)

如果我想对 mdply 做同样的事情,它不起作用,因为 mdply 中的函数需要从数据框或数组的列中获取值。 Mapply 将列表作为输入。

这些 plyr apply 函数很方便,不仅因为我可以获得 data.frame 的输出,还因为我可以使用进度条。

我知道有 pbapply 包,但没有 mapply 版本,也有 txtProgressBar 函数,但我不知道如何将它与 mapply 一起使用。

我试图创建一个可重现的示例(需要大约 30 秒才能完成 运行)

我猜是坏榜样。我的 l1 是一个被抓取的网站列表 (rvest::read_html),我无法将其作为数据帧发送到 mdply。列表确实需要列表。

mdply <- plyr::mdply

l1 <- as.list(rep("a", 2*10^6+1))
l2 <- as.list(rnorm(-10^6:10^6))

my_func <- function(x, y) {

ab <- paste(x, "b", sep = "_")
ab2 <- paste0(ab, exp(y), sep = "__")

return(ab2)

}

mapply(my_func, x = l1, y = l2)

mdply 不起作用

mdply(l1, l2, my_func, .progress='text')

Error in do.call(flat, c(args, list(...))) : 'what' must be a function or character string

来自?mdply 我敢说你不能指定两个数据输入。您的错误消息意味着 mdply 正在尝试将 l2 用作函数,但无法将列表强制转换为函数...

以下工作正常

mdply(
    data.frame(x=unlist(l1), y=unlist(l2)), # create a data.frame from l1 and l2
    my_func, # your function
    .progress=plyr::progress_text(style = 3) # create a textual progress bar
)[, 3] # keep the output only

我想我现在已经明白你的目的了:

mdply(
    .data=data.frame(r=1:length(l1)), # "fake data" (I will use them as item index)
    .fun=function(r) return(my_func(l1[[r]], l2[[r]])), # a wrapper function of your function
    .progress=plyr::progress_text(style = 3) # create a textual progress bar
)[, 2] # keep the output only

请注意,我不得不用一个只考虑一个参数的新函数包装你的函数,它使用该参数访问 l1l2

回答我自己的问题。 现在有一个包可以做到这一点。它被称为pbapply。我正在寻找的功能是 pbmapply。