dnagirl
dnagirl

Reputation: 20456

Generate a repeating sequence

I need to generate a vector of the following format using R:

1:10, 1:10, 11:20, 11:20, ... 121:130, 121:130

Is there an easier way than creating 12 vectors and then repeating each one twice?

Upvotes: 4

Views: 15817

Answers (6)

lmo
lmo

Reputation: 38500

A method using split is

unlist(rep(split(seq_len(130), rep(1:13, each=10)), each=2), use.names=FALSE)

Upvotes: 1

Marek
Marek

Reputation: 50704

Another way:

x <- matrix(1:130, 10, 13)
c(rbind(x, x))

Possible more efficient version:

x <- 1:130
dim(x) <- c(10,13)
c(rbind(x, x))

Upvotes: 3

nullglob
nullglob

Reputation: 7023

Alternatively, you could use a combination of rep and outer, such as:

c(outer(1:10,rep(0:12,each=2),function(x,y)10*y+x))

Upvotes: 2

nico
nico

Reputation: 51640

Also you could do:

rep(1:10, 26) + rep(seq(0,120,10), each=20)

Upvotes: 18

Shane
Shane

Reputation: 100164

Is this what you want?

unlist(lapply(rep(seq(1, 121, by=10), each=2), function(x) seq(x, x+9)))

Upvotes: 3

JoFrhwld
JoFrhwld

Reputation: 9037

I think this will do you.

x <- ((0:12)*10)+1
y <- x + 9

repeatVectors <- function(x,y){
    rep(seq(x,y),2)
}

z <- mapply(repeatVectors, x,y)
z <- as.vector(z)

Upvotes: 1

Related Questions