2017-09-06 43 views
0

當使用l_ply將函數應用於列表的每個元素時,如何生成顯示列表中元素編號的輸出,該函數是暫時應用於? 它類似於一個進度條(l_dply(list, function, .progress = progress_text(char = '*')),但我想在目前正在函數處理列表中的元素的位置的指標。列表`l_dply`的元素的輸出編號應用函數

例如,如果我的列表中有100元,我對於每次迭代應用都會輸出從1到100的函數

我使用的是帶有下載功能的l_ply,所以我的最終目標是能夠找出哪個列表元素下載不起作用

+0

不知道這將是最好的辦法。您應該查看http://r4ds.had.co.nz/iteration.html#dealing-with-failure。 –

+0

是這樣的嗎? https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun如果我需要這樣的東西,我通常訴諸於for循環或'mapply',其中一個變量是一個「迭代器列表「而第二個是我正在嘗試處理的事情。哦,這裏是Ana提到的解決方案:https://stackoverflow.com/a/29833989/322912 –

回答

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" 

編輯:

我固定它用省略號(...)工作,這是醜陋的,雖然,那種醜陋的,通常讓我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 
+0

相關:https://stackoverflow.com/questions/12982528/how-to-create-an-r-function-編程 –