Repeat vector by a vector number of times

Viewed 39

Let's consider string vector:

string_vector <- c("big & huge", "big & huge & small", "tiny",
                   "very_small & tremendous")

and the other vector containing integers:

number <- c(2, 1, 3, 4)

I want to repeat element of string_vector by number of times equal to corresponding integer in number vector. i.e. string_vector[1] repeat number[1] times, string_vector[2] repeat number[2] times and so on.

My solution

My solution is most straightforward as possible:

vec <- c()
for (i in seq_len(length(number))) {
  vec <- append(vec, rep(string_vector[i], number[i]))
}

Problem

My problem is that my solution is little bit inconvenient. I'm thinking if it's possible to omit loop somehow. I'm not so sure how it can be done. Do have any idea how this problem can be solved by not using loop ?

2 Answers

If I'm not mistaken the solution is this:

rep(string_vector,number)
 [1] "big & huge"              "big & huge"              "big & huge & small"      "tiny"                   
 [5] "tiny"                    "tiny"                    "very_small & tremendous" "very_small & tremendous"
 [9] "very_small & tremendous" "very_small & tremendous"

The loop isn't necessary at all, thanks to the wonderful Map().Map applies a function to the corresponding elements of given vectors. Using your data you can do something like this:

v <- unname(unlist(Map(function(x,y)rep(x,y),string_vector,number)))
identical(v,vec)

Map by default return a named list, so with unname(unlist()) you can obtain the vector your looking for. I invite you to look the help page for the function because it will make your life easier in many cases.

Related