[R] matrix() Help

Marc Schwartz MSchwartz at medanalytics.com
Tue Feb 24 18:50:20 CET 2004


On Tue, 2004-02-24 at 10:51, Jonathan Wang wrote:
> I have a question related to matrix().
> 
> The code below randomly generates 3 Poisson numbers into a 3 by 1
> matrix:
> 
> > matrix1 <- matrix(rpois(3,lambda=2),nrow=3,ncol=1)
> 
> And I use list() to see what they are:
> 
>      [,1]
> 
> [1,]  3
> 
> [2,]  1
> 
> [3,]  4
> 
> , which is what I had intended.
> 
> I then I want to randomly generate y Normal numbers into a 3 by 8
> matrix. y in this case would be 3, 1, and 4; so the resulting matrix
> should be such that the first row has three different Normal numbers;
> the second row has 1 Normal number; and the third row has four
> different Normal numbers. I have the following code to do that:
> 
> > matrix2 <- matrix(rnorm(poisNums),nrow=3,ncol=8)
> 
> To my surprise, matrix2 does not look anything like what I had
> intended. Instead, it repeats the values in the first column (of the
> matrix2) eight times. What part of the code do I need to fix?


See the help for rnorm(), which says:

n: number of observations. If 'length(n) > 1', the length is
          taken to be the number required.

Thus, by using rnorm(matrix1), you get 3 numbers back, which is the
length of matrix1. Since 3 is less than 24 (3 x 8), the vector from
rnorm is cycled to fill in the matrix.

Use lapply() and have the final result be a 'list', since the number of
values in each component will vary:

matrix1 <- matrix(rpois(3, lambda = 2), nrow = 3, ncol = 1)
> matrix1
     [,1]
[1,]    5
[2,]    3
[3,]    1

list2 <- lapply(matrix1, rnorm)

> list2
[[1]]
[1] -1.186458639  1.096777044 -0.005344028  0.707310667  1.034107735

[[2]]
[1]  0.2234804 -0.8787076  1.1629646

[[3]]
[1] -2.000165

See ?lapply

Watch out for situations where an element in matrix1 is a zero. You will
get a numeric(0) as a result in that list element.

HTH,

Marc Schwartz




More information about the R-help mailing list