Skip to content

sample "n" random positions from a matrix

5 messages · Milton Cezar Ribeiro, Paul Smith, Francisco J. Zagmutt +1 more

#
On 12/10/06, Milton Cezar Ribeiro <milton_ruser at yahoo.com.br> wrote:
Do you mean extracting the indexes of n randomly chosen elements of
the matrix which are equal to one?

Paul
#
Milton,

If I understand your problem correctly, you want to take (and store) a 
random sample of the indexes of a matrix for values equal to 1.  If 
that's the case the following may work for you:

m=matrix(sample(c(0,1),100*100,replace=T),nrow=100,ncol=100) #Creates matrix

idxsample=function(m,n){
   idx=which(m==1,F)#Index of positions of 1's in the matrix
   pos=sample(idx,n,replace=F)#Random sample of matrix indexes
   return(pos)
}

This call will sample and store 20 "positions" with value==1 in your matrix
pos=idxsample(m,n=20)

you can then use the resulting object to retrieve the values from your 
matrix i.e.
m[pos] (not surprisingly, all == 1)


I hope this helps,

Francisco


Dr. Francisco J. Zagmutt
College of Veterinary Medicine and Biomedical Sciences
Colorado State University
Milton Cezar Ribeiro wrote:
#
On Sun, 10 Dec 2006, Milton Cezar Ribeiro wrote:

            
Is this what you want?
row col
[1,]  99  99
[2,]  93  93
[3,]  36  36
[4,]  74  74
[5,]  11  11
[6,]   3   3
[7,]  21  21
[...]

Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717
#
On Sun, 10 Dec 2006, Charles C. Berry wrote:

            
OOPS! That only works when there is exactly one one in each row. This is 
what is needed generally:
row col
[1,]  82  82
[2,]  36  36
[3,]  54  54
[4,]  89  89
[5,]  88  88
[6,]  52  52
[7,]  65  65
Charles C. Berry                        (858) 534-2098
                                          Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	         UC San Diego
http://biostat.ucsd.edu/~cberry/         La Jolla, San Diego 92093-0717