使用l_ply
将函数应用于列表的每个元素时,如何生成一个输出,显示函数暂时应用的列表元素的编号?
它与进度条(l_dply(list, function, .progress = progress_text(char = '*'))
类似,但我想要的是该函数当前正在处理的列表中元素位置的指示符。
例如,如果我的列表有100个元素,我想在每次迭代时输出1到100的函数。
我正在使用带有下载器功能的l_ply
,所以我的最终目标是能够找到下载不起作用的列表元素。
答案 0 :(得分:1)
也许这对你有用:
l_ply2<- function(.data, .fun = NULL, ..., .progress = "none", .inform = FALSE,
.print = FALSE, .parallel = FALSE, .paropts = NULL){
i <- 0
fun2 <- function(x){
i <<- i+1
print(i)
.fun(x)
}
plyr::l_ply(.data, fun2, ..., .progress = .progress, .inform = .inform,
.print = .print, .parallel = .parallel, .paropts = .paropts)
}
l_ply2(list("a","b","c"),print)
# [1] 1
# [1] "a"
# [1] 2
# [1] "b"
# [1] 3
# [1] "c"
编辑:
我修复了它以使用省略号(...
),但它很丑陋,这种丑陋通常会让我失败:)无论如何,这里有,如果可以,请帮我制作它美丽:
l_ply2<- function(.data, .fun = NULL, ..., .progress = "none", .inform = FALSE,
.print = FALSE, .parallel = FALSE, .paropts = NULL){
i <- 0
str <- paste0(deparse(args(.fun))[1],
"{i<<-i+1;print(i);",
as.character(substitute(.fun)),
"(",paste(paste(formalArgs(.fun),"=",formalArgs(.fun)),collapse=","),")}")
fun2 <- eval(parse(text = str))
plyr::l_ply(.data, fun2, ..., .progress = .progress, .inform = .inform,
.print = .print, .parallel = .parallel, .paropts = .paropts)
}
l_ply2(list("a","b","c",123.456),print,digits=4)
# [1] 1
# [1] "a"
# [1] 2
# [1] "b"
# [1] 3
# [1] "c"
# [1] 4
# [1] 123.5