tags:

views:

139

answers:

5

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?

+1  A: 

Is this what you want?

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

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)
JoFrhwld
this gives the answer I'm looking for too. Tx!
dnagirl
+11  A: 

Also you could do:

rep(1:10, 26) + rep(seq(0,120,10), each=20)
nico
+1 Nice solution!
Shane
elegant! And given the number of ways to get to the result, I'm feeling a bit better about being flummoxed.
dnagirl
Very nice, I like this one
Pierreten
Even rep(1:10, 2) + rep(seq(0,120,10), each=20) will work
Jyotirmoy Bhattacharya
rats, came to this late and thought I had the fastest but this is so close to the optimal solution I'm just voting it up. To make it even faster use "rep(0:12, each = 20)*10" after the + sign. (6x speedup overall)
John
further to the speed issue - this answer is 5x faster than lapply()). The outer() answer below falls between this answer and my modification in performance. The newer matrix answer is about equal in speed to my modification here and perhaps the fastest overall.
John
And one more modification: `1:10 + rep(10*(0:12), each=20)`.
Marek
+1  A: 

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))
nullglob
+2  A: 

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))
Marek
fastest solution possible.
John