[R] Samplng from a matrix (was: no subject)

Marc Schwartz marc_schwartz at comcast.net
Wed Mar 28 15:34:43 CEST 2007


On Wed, 2007-03-28 at 15:46 +0300, kaloytyn at cc.jyu.fi wrote:
> Hallo,
> 
> I'm trying to sample a matrix with simple random sampling without
> replacement but seem to have a problem with the matrix length. Both
> sample() and srswor() use length() which returns the number of columns in
> matrix. This means that to function it seems that the sample size exceeds
> the matrix length. I need to sample the whole matrix for there are
> auxiliary variables I need for further sample processing. Ay help is much
> appreciated.
> 
> Regards,
> Katja Löytynoja

First, please use an informative subject line in your posts to aid in
folks searching the list archives.

It is not clear whether you want to randomly sample individual values in
the matrix, random rows or random columns.

Using:

mat <- matrix(1:64, ncol = 8)

> mat
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    9   17   25   33   41   49   57
[2,]    2   10   18   26   34   42   50   58
[3,]    3   11   19   27   35   43   51   59
[4,]    4   12   20   28   36   44   52   60
[5,]    5   13   21   29   37   45   53   61
[6,]    6   14   22   30   38   46   54   62
[7,]    7   15   23   31   39   47   55   63
[8,]    8   16   24   32   40   48   56   64



1. Sample 10 values:

> sample(mat, 10)
 [1] 28  5 34 43 44 41 11 35 25 30


2. Sample 4 rows out of the 8:

> mat[sample(8, 4), ]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    4   12   20   28   36   44   52   60
[2,]    8   16   24   32   40   48   56   64
[3,]    3   11   19   27   35   43   51   59
[4,]    5   13   21   29   37   45   53   61


3. Sample 4 columns out of the 8:

> mat[, sample(8, 4)]
     [,1] [,2] [,3] [,4]
[1,]   17   57    9   41
[2,]   18   58   10   42
[3,]   19   59   11   43
[4,]   20   60   12   44
[5,]   21   61   13   45
[6,]   22   62   14   46
[7,]   23   63   15   47
[8,]   24   64   16   48


The key is to use sample() to generate random indices into the matrix
and to use matrix indexing appropriately.

HTH,

Marc Schwartz



More information about the R-help mailing list