[R] matrix problem
David Winsemius
dwinsemius at comcast.net
Sat Jul 4 17:49:22 CEST 2009
On Jul 4, 2009, at 11:17 AM, William Simpson wrote:
> Can anybody please tell me a good way to do the following?
>
> 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
You ought to separate those assignments with semicolons:
x=c(1,2); nrow=5; ncol=4
> MM <- matrix( c(x,rep(0, nrow-length(x)+1)), nrow=nrow, ncol=ncol)
Warning message:
In matrix(c(x, rep(0, nrow - length(x) + 1)), nrow = nrow, ncol =
ncol) :
data length [6] is not a sub-multiple or multiple of the number of
rows [5]
> MM
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 2 1 0 0
[3,] 0 2 1 0
[4,] 0 0 2 1
[5,] 0 0 0 2
OR------
> M2 <- diag( , nrow=5, ncol=4)
> M2[row(M2) == col(M2)+1] <- 2
> M2
[,1] [,2] [,3] [,4]
[1,] 1 0 0 0
[2,] 2 1 0 0
[3,] 0 2 1 0
[4,] 0 0 2 1
[5,] 0 0 0 2
>
> 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
>
> ______________________________________________
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list