osmirnov at notes.cc.sunysb.edu
2008-Apr-28 16:12 UTC
[R] choosing a random element from a vector
I have a vector consisting of zeroes and ones, e.g. 101001. I would like to pick a random element from this vector equal to one. In the example above, that means that only elements 1, 3, or 6 can be chosen. Is there a simple and fast way to do that? (my vector of zeroes and ones is very large) Thank you. --------------------------------------------------------- Oleg Smirnov Assistant Professor of Political Science Stony Brook University [[alternative HTML version deleted]]
Try this: x <- sample(0:1, rep = TRUE, 1e6, prob=c(0.4, 0.6)) sample(which(x == 1), 1) On Mon, Apr 28, 2008 at 1:12 PM, <osmirnov@notes.cc.sunysb.edu> wrote:> > I have a vector consisting of zeroes and ones, e.g. 101001. > > I would like to pick a random element from this vector equal to one. In > the > example above, that means that only elements 1, 3, or 6 can be chosen. > > Is there a simple and fast way to do that? (my vector of zeroes and ones > is > very large) > > Thank you. > > --------------------------------------------------------- > Oleg Smirnov > Assistant Professor of Political Science > Stony Brook University > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@r-project.org 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. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]