[R] sample unique pairs from a matrix

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Thu May 28 12:58:17 CEST 2009


> I have a matrix of both negative and positive values that I would like
> to randomly sample with the following 2 conditions:
> 
> 1. only sample positive values
> 2. once a cell in the matrix has been sampled the row and column of
> that cell cannot be sampled from again.
> 
> #some dummy data
> set.seed(101)
> dataf <- matrix(rnorm(36,1,2), nrow=6)
> 
> I can do this quite simply if all the values are positive by using the
> sample function without replacement on the column and row indices.
> 
> samrow <- sample(6,replace=F)
> samcol <- sample(6,replace=F)
> values <- numeric(6)
> for(i in 1:6){
>    values[i] <- dataf[samrow[i], samcol[i]]
> }
> 
> However, I am not sure how to include the logical condition to only
> include postitive values

You could create a new variable containing only the positive values of 
dataf, and sample from that, e.g.
dataf <- matrix(rnorm(36,1,2), nrow=6)
posdata <- dataf[dataf > 0]
sample(posdata, 6, replace=FALSE)

Regards,
Richie.

Mathematical Sciences Unit
HSL


------------------------------------------------------------------------
ATTENTION:

This message contains privileged and confidential inform...{{dropped:20}}




More information about the R-help mailing list