Home > Enterprise >  Print function in map behaves differently than in for loop in R
Print function in map behaves differently than in for loop in R

Time:08-22

I am just practicing basic for loops to compare against their purrr::map() equivalent. However I am lost why the simple print function appears to double the output vs. its equivalent for loop.

#this simple for loop behaves as expected and gives us the numbers 1 through 10.
.x <- 1:10

for (i in .x){
  print(i)
}
#result
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10


#this doubles the output in an embedded list - I don't understand why

map(.x=.x,~print(.x))


#results below
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

[[6]]
[1] 6

[[7]]
[1] 7

[[8]]
[1] 8

[[9]]
[1] 9

[[10]]
[1] 10

I would have though they would produce the same (however I know the map results would be in a list unless I specify the output (eg. map_chr or map_df).

CodePudding user response:

According to R documentations print prints its argument and returns it invisibly (via invisible(x)).

So your map function is essentially doing

.x <- 1:10

funcy <- function() {
  out = list()
  
  for (i in .x){
    
    out[[i]] = print(i)
  }
  return(out)
}

funcy()

The print function gets called every loop and when the loop ends the function returns the stored values in a list

CodePudding user response:

The purrr library has a function specifically designed for tasks such as this: walk.

If you don't want to return anything and are only calling functions for the purpose of their downstream effects (print or write_csv), you can use walk instead of map.

walk(1:10, print)

# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
# [1] 6
# [1] 7
# [1] 8
# [1] 9
# [1] 10
  • Related