[R] matrix problem

Charles C. Berry cberry at tajo.ucsd.edu
Sat Jul 4 17:58:30 CEST 2009


On Sat, 4 Jul 2009, William Simpson wrote:

> Can anybody please tell me a good way to do the following?

Not sure how you want cases like x = 1:3, nrow=2 , ncol=7 to be handled, 
but for the example you give, this works:

mat <- matrix(0,nr=nrow,nc=ncol)
indx <- outer(
 		seq( from=0, length=length(x) ),
 		seq( from=1, by=nrow+1, length=ncol ), "+" )
mat[ indx ] <- x


HTH,

Chuck

>
> Given a vector, number of rows and number of columns, return a matrix
> as follows. Easiest to give an example:
>
> x=c(1,2), nrow=5, ncol=4
>
> return the matrix:
>
>   1 0 0 0
>   2 1 0 0
>   0 2 1 0
>   0 0 2 1
>   0 0 0 2
>
> Thanks very much for any help!
> Bill
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901




More information about the R-help mailing list