[R] Help with a problem

Gavin Simpson gavin.simpson at ucl.ac.uk
Sat Sep 15 18:42:58 CEST 2007


On Sat, 2007-09-15 at 12:11 -0400, Letticia Ramlal wrote:
> Hello 
> I was wonderinf if anyone can help me with this problem, it seems
> trivial but for some reason I can not figure it out.
>  
> With a single R command complete the following:
> create a vector calles seqvec that repeats the sequence 1, 3,6,
> 10,15,21.( I was trying to use c() but this does not work) 
> create a 5-row, 6-column matirx from seqvec wuth each row containg the
> sequence from before 
> and complete the two task above in a single step.

If that is just an example of an arbitrary sequence, then the following
does what you want:

> res <- matrix(rep(c(1,3,6,10,15,21), 5), nrow = 5, byrow = TRUE)
> res
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    3    6   10   15   21
[2,]    1    3    6   10   15   21
[3,]    1    3    6   10   15   21
[4,]    1    3    6   10   15   21
[5,]    1    3    6   10   15   21

But if there is something special in the quoted sequence (it is
cumsum(1:6) ), then the following also does what you want:

> res2 <- matrix(rep(cumsum(1:6), 5), nrow = 5, byrow = TRUE)
> res2
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    3    6   10   15   21
[2,]    1    3    6   10   15   21
[3,]    1    3    6   10   15   21
[4,]    1    3    6   10   15   21
[5,]    1    3    6   10   15   21
> all.equal(res, res2)
[1] TRUE

Take a look at ?rep and, although not needed in this case, ?seq for
generating sequences and repeats.

HTH

G

>  
> LTR
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Gavin Simpson                 [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%



More information about the R-help mailing list