Working with map function and vectors in R

Viewed 195

I am trying to understand the working of vectors with purrr::map() function. I have a vector c("cat", "fish", "hamster") and I want to convert it into the following output:

[[1]]
[1] "cat" "cat" "cat"

[[2]]
[1] "fish" "fish"

[[3]]
[1] "hamster"

Not sure about which map() function should I use and how to approach it. I find it as repetition of the first element thrice, 2 element twice and 3 third element just once.

4 Answers

We don't need a package for this. It would be faster with rep and split

v2 <- rep(v1, length(v1):1)
split(v2, v2)
#$cat
#[1] "cat" "cat" "cat"

#$fish
#[1] "fish" "fish"

#$hamster
#[1] "hamster"

Or use imap

library(purrr)
rev(imap(rev(v1), ~ rep(.x, .y)))

data

v1 <- c("cat", "fish", "hamster")

You could use:

x <- c("cat", "fish", "hamster")
map2(x, 3:1, rep)

Another base R option using Map + replicate

> Map(replicate, rev(seq_along(v)), v)
[[1]]
[1] "cat" "cat" "cat"

[[2]]
[1] "fish" "fish"

[[3]]
[1] "hamster"

In base R you could use mapply:

v <- c("cat", "fish", "hamster")
mapply(rep, v, 3:1)

Or with pmap:

purrr::pmap(list(v, 3:1), rep)
Related