[R] sample "n" random positions from a matrix
Francisco J. Zagmutt
gerifalte28 at hotmail.com
Mon Dec 11 03:35:01 CET 2006
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:
> Hi there,
>
> I have a binary matrix (dim 100x100) filled with values 0 and 1. I need select a record "n" positions of that matrix when values are 1. How can I do that?
>
> Thanks for all,
> Miltinho
> Brazil
>
>
> ---------------------------------
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list