Generating an vector with rep and seq but without the c() function

154 Views Asked by At

Suppose that I am not allowed to use the c() function.

My target is to generate the vector

"1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9"

Here is my attempt:

rep(seq(1, 5, 1), 5)

# [1] 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5

rep(0:4,rep(5,5))

# [1] 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4

So basically I am sum them up. But I wonder if there is a better way to use rep and seq functions ONLY.

4

There are 4 best solutions below

0
Maël On BEST ANSWER

Like so:

1:5 + rep(0:4, each = 5)
# [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

I like the sequence option as well:

sequence(rep(5, 5), 1:5)
0
jay.sf On

You could do

rep(1:5, each=5) + rep.int(0:4, 5)
# [1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9

Just to be precise and use seq as well:

rep(seq.int(1:5), each=5) + rep.int(0:4, 5)

(PS: You can remove the .ints, but it's slower.)

0
B. Christian Kamgang On

One possible way:

as.vector(sapply(1:5, `+`, 0:4))

[1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9
0
asd-tm On

I would also propose the outer() function as well:

library(dplyr) 
outer(1:5, 0:4, "+") %>%
array() 

Or without magrittr %>% function in newer R versions:

outer(1:5, 0:4, "+") |>
    array() 
        

Explanation.

The first function will create an array of 1:5 by 0:4 sequencies and fill the intersections with sums of these values:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    3    4    5    6
[3,]    3    4    5    6    7
[4,]    4    5    6    7    8
[5,]    5    6    7    8    9

The second will pull the vector from the array and return the required vector:

[1] 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 4 5 6 7 8 5 6 7 8 9