Brief purrr:map_xxx question

is there a reason why the following doesn't work:

> map_chr(.x = c("spades", "hearts", "clubs", "diamonds"), rep, 13)
Error: Result 1 is not a length 1 atomic vector

(ie, the code attempts to map the rep() function to the vector .x, passing 13 as ... to rep().)

but this does work:

map(.x = c("spades", "hearts", "clubs", "diamonds"), rep, 13) %>% unlist()

Based on the docs, I thought the whole point of the map_xxx functions was to return vectors.

In your first example using map_chr(), each operation returns a character vector of length 13, which is not a valid entry into a character vector. Only by catenating them or unlisting a list containing them (as you've done in the second example), can you get a character vector back.

What's the reason for using map() in the first place when it seems like you want rep(c("spades", "hearts", "clubs", "diamonds"), each = 13)? Or were you just casting about for an example?

2 Likes

map_chr() collect "a string element" from each iteration by function, then return the collect of the strings as list.

The function rep() does not returns an string element but returns a list of strings so, map_chr() makes an error.

1 Like

Right, so rather than using map_chr() (which returns a character vector), you can use map() which will return a list. From the purrr cheat sheet :arrow_down:
purrr_output

1 Like

It easier to answer question about a piece of code that doesn't work if you also include what you expect it to produce.

Just a guess but it looks like you want to produce 13 * 4 elements in your output, i.e. 52 the number of cards in deck.

But map and friends returns 1 output element for each element in the input so the map function you are using will return 4 elements in a list so you need an extra operation like this...

map(c("spades", "hearts", "clubs", "diamonds"), rep, 13) %>% flatten_chr(.)

This produces character vector with 13 * 4 + 52 elements in it.

This is an alternative syntax

map(c("spades", "hearts", "clubs", "diamonds"), ~ rep(.x, 13)) %>% flatten_chr(.)

which makes it easier to see what is happening with rep (just IMHO) because you need not know what map is doing with that "extra" argument :slight_smile:

If you are looking for some other kind of result just get back to us.

2 Likes

Casting about is certainly my usual MO. In this case, yes, I wanted a simple ex but think I outsmarted myself in the process. Thank you for the answer and for this terrific community site.