简体   繁体   中英

Understanding purrr map output

Having a little trouble wrapping my head around what is returned by map

map(1:3, print)
[1] 1
[1] 2
[1] 3
[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

The first three outputs make sense, as they match what is returned from manually putting in

print(1)
print(2)
print(3)

Following this it seems to be some kind of nested list. Is there any way to get just one or the other?

Any help would be appreciated!

So I think what is going on is that map returns a list and print returns to the console. So what you're seeing is the return of both print and map . It becomes really apparent when you assign this to a variable.

library(purrr)

#no assignment, both returns
map(1:3, ~print(.x))
#> [1] 1
#> [1] 2
#> [1] 3
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 3

x <- map(1:3, ~print(.x))
#> [1] 1
#> [1] 2
#> [1] 3


x
#> [[1]]
#> [1] 1
#> 
#> [[2]]
#> [1] 2
#> 
#> [[3]]
#> [1] 3

You can see here that even though you assigned map(1:3, ~print(.x)) to a variable, print still returns 1:3 to the console and the variable x holds the values of 1:3 in a list.

With purrr you can specify what output you want to get, like this:

map_int(1:3, print)

#[1] 1
#[1] 2
#[1] 3
#[1] 1 2 3

See ?map to get all the possible outcomes. Of course it will throw an error if the outcome you want doesn't make sense, like map_lgl(1:3, print) , for example.

This is very useful when you use map inside of custom functions, because you can control the output, and catch an error if something goes wrong.

Of course you can use map alone, but like in your example, is better to use something more precise ( map_int , map_df , map_char , ecc.).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM