也許這會適合你:
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"
編輯:
我固定它用省略號(...
)工作,這是醜陋的,雖然,那種醜陋的,通常讓我downvotes :),反正這裏有雲,如果你能,幫我做這美麗:
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
不知道這將是最好的辦法。您應該查看http://r4ds.had.co.nz/iteration.html#dealing-with-failure。 –
是這樣的嗎? https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun如果我需要這樣的東西,我通常訴諸於for循環或'mapply',其中一個變量是一個「迭代器列表「而第二個是我正在嘗試處理的事情。哦,這裏是Ana提到的解決方案:https://stackoverflow.com/a/29833989/322912 –