[R] sample unique pairs from a matrix
David Winsemius
dwinsemius at comcast.net
Thu May 28 13:17:28 CEST 2009
On May 28, 2009, at 6:33 AM, jos matejus wrote:
> Dear R users,
>
> 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
> Any help would be gratefully received.
> Jos
> M <- matrix(rnorm(36),nrow=6)
> M[M[,]>0]
[1] 1.65619781 0.56182830 0.23812890 0.81493915 1.01279243
1.29188874 0.64252343 0.53748655 0.31503112
[10] 0.37245358 0.07942883 0.56834586 0.62200056 0.39478167 0.02374574
0.04974857 0.56219171 0.52901658
> sample(M[M[,]>0],6,replace=F)
[1] 0.56834586 0.07942883 0.31503112 0.62200056 0.02374574 0.64252343
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list