[R] How to generate a particular sequence ?

Keith Jewell k.jewell at campden.co.uk
Mon Sep 13 11:57:18 CEST 2010


"Ted Harding" <Ted.Harding at manchester.ac.uk> wrote in message 
news:XFMail.100913104250.Ted.Harding at manchester.ac.uk...
> On 13-Sep-10 09:19:21, Feng Li wrote:
>> Dear R,
>> I have a vector, say a = c(1,2,4,5,6,8). Can I generate a vector
>> or array (2-by-3-by-3) of this form
>> c(1,2,1,2,1,2,4,5,4,5,4,5,6,8,6,8,6,8)
>> in which every two elements in "a" have been repeated twice?
>>
>> I am to stupid today and could not figure this simple question out...
>> Many many thanks!
>>
>> Feng
>
> A possible solution (somewhat generalisable):
>
>  a <- c(1,2,4,5,6,8)
>  Reps <- 3
>
>  pairs <- matrix(a,nrow=2)
>  as.vector(pairs[,rep(c(1,2,3),each=Reps)])
>  # [1] 1 2 1 2 1 2 4 5 4 5 4 5 6 8 6 8 6 8
>
> (By the way, you have 3 repetitions but wrote "twice" -- I assume
> you meant "thrice" but the above generalises to 2 repetitions ... :)
>
> Ted.
The pedant in me couldn't resist asking:
  If he'd said "repeated once" would you expect only one occurence of each 
pair?

Sorry. I'll get my coat....

Keith J



More information about the R-help mailing list