MyQ
MyQ

Reputation: 469

Fast way of generating sequence of numbers in R

It may look like a funny question but what is the fastest way in R to generate a 2 rows matrix like below:

cc = NULL
n1 = 1000
n2 = 1000000
  for (i in 0:n1)
    for (j in 0:n2)
      cc = c(cc, i, j)
  cbn = matrix(cc, nrow = 2)

Upvotes: 2

Views: 124

Answers (1)

James B
James B

Reputation: 474

Generally you want to avoid for loops and building vectors via "c" over and over. Here's one way to do that.

n1 <- 3
n2 <- 4

rbind(rep(0:n1, each = n2 + 1), rep(0:n2, n1 + 1))

Upvotes: 6

Related Questions