2

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.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • 1
    Why can't you use `c()`? It is an odd constraint and I'm not sure it makes sense. Everything in R is a vector so you can't prohibit the use of functions which create vectors. So can you do `1:3`? Or `rbind(1,2,3) |> as.integer()`? I don't understand the rules of this really. – SamR Oct 05 '22 at 17:02
  • Sorry, but it is the question setting constraint to me. – PowerPoint Trenton Oct 05 '22 at 17:08

4 Answers4

4

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)
Maël
  • 45,206
  • 3
  • 29
  • 67
3

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.)

jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

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
1

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
asd-tm
  • 3,381
  • 2
  • 24
  • 41