I am trying to catch up with the purrr::walk, but feel little bit confused. Please find the toy example, and advise where I go wrong.

library(purrr)# ordinary lapplylp = 1lp2 <- lapply(1:10, function(c) {lp <<- lp + cprint(lp)}) %>% invisiblelp # 56lp2 # a list up to 56# purrr::mapmp = 1mp2 <- map(.x = 1:10,.f = function(c) {mp <<- mp + cprint(mp[[1]])}) %>% invisiblemp # 56mp2 # a list up to 56wk = 1wk2 <- walk(.x = 1:10, .f = function(c) {wk <<- wk +cprint(wk)return(wk)})wk #56wk2 # a vector up to 10# that confuses me, shouldn't it be as much as wk2?

By the way, with such short example, it doesn't show much difference in performance

library(microbenchmark)microbenchmark(lp2, mp2, wk2, times = 10000)#> microbenchmark(lp2, mp2, wk2, times = 10000)#Unit: nanoseconds# expr min lq mean median uq max neval# lp2 39 47 55.1047 49 56 15738 10000# mp2 40 47 59.2899 49 56 15661 10000# wk2 39 47 57.4763 50 56 15629 10000
1

Best Answer


Thanks to @JosephWood, it turns out that I didn't read the doc close enough.I love th community!

as @andrew_reece suggests, here is my understanding from this case.

purrr::walk is as named, it proceeds step by step. What it concerns is to go through all the steps assigned. As to the result, the result is the side effect happening when the function walks.

Therefore, the return value simply announces "I'd finished the steps you asked for".

wk = 1wk2 <- walk(.x = 1:10, .f = function(c) {wk <<- wk +c ## do something while walking,## and pass out the result to tell what you've done.print(wk)return(wk)})wk #56 <- the final result of the side effect.wk2 # 1 2 3 4 5 6 7 8 9 10# I'd finished the 10 steps you asked.

purrr::map, and its siblings, as apply family, are focusing on doing this for certain times, in certain manners, and returns the values it obtains when it marches forward.