# [R] Matrix

David L Carlson dcarlson at tamu.edu
Tue Mar 7 16:46:45 CET 2017

```Change the "4" in embed(c(0*x[-1], x, 0*x[-1]), 4) to length(x) and it will generalize to other length vectors. This solution is not as compact, but it illustrates a relatively obscure R function:

> x <- 1:4
> ncol <- length(x)
> zeros <- rep(0, ncol - 1)
> toeplitz(c(zeros, x, zeros))[-(1:(ncol-1)), 1:ncol]
[,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    2    1    0    0
[3,]    3    2    1    0
[4,]    4    3    2    1
[5,]    0    4    3    2
[6,]    0    0    4    3
[7,]    0    0    0    4

-------------------------------------
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352

-----Original Message-----
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Gabor Grothendieck
Sent: Tuesday, March 7, 2017 7:21 AM
To: Peter Thuresson <peter.thuresson at umea.se>
Cc: R-help at r-project.org
Subject: Re: [R] Matrix

Assuming that the input is x <- 1:4, try this one-liner:

> embed(c(0*x[-1], x, 0*x[-1]), 4)
[,1] [,2] [,3] [,4]
[1,]    1    0    0    0
[2,]    2    1    0    0
[3,]    3    2    1    0
[4,]    4    3    2    1
[5,]    0    4    3    2
[6,]    0    0    4    3
[7,]    0    0    0    4

On Mon, Mar 6, 2017 at 11:18 AM, Peter Thuresson
<peter.thuresson at umea.se> wrote:
> Hello,
>
> Is there a function in R which can transform, let say a vector:
>
> c(1:4)
>
> to a matrix where the vector is repeated but "projected" +1 one step down for every (new) column.
> I want the output below from the vector above, like this:
>
> p<-c(1,2,3,4,0,0,0,0,1,2,3,4,0,0,0,0,1,2,3,4,0,0,0,0,1,2,3,4)
>
> matrix(p,7,4)
>

--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

______________________________________________
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help