Re: [R] Randomly select elements based on criteria

2012-03-23 Thread Petr Savicky
On Fri, Mar 23, 2012 at 10:56:11AM +0100, Petr Savicky wrote: > On Thu, Mar 22, 2012 at 11:42:53AM -0700, aly wrote: [...] > > I want to randomly select two rows but they have to be from different fam. > > The fist part (random selection), I got it by doing: > > > > > ran <- sample(nrow (fish), si

Re: [R] Randomly select elements based on criteria

2012-03-23 Thread Petr Savicky
On Thu, Mar 22, 2012 at 11:42:53AM -0700, aly wrote: > Hi, > > I want to randomly pick 2 fish born the same day but I need those > individuals to be from different families. My table includes 1787 fish > distributed in 948 families. An example of a subset of fish born in one > specific day would l

Re: [R] Randomly select elements based on criteria

2012-03-22 Thread Peter Ehlers
Here's another way: With d1 as your data frame, library(plyr) d2 <- ddply(d1, .(fam), function(x) x[sample(nrow(x), 1), ]) d2[sample(nrow(d2), 2), ] If you have to take account of the 'only one family' case, you can wrap this in a function with an appropriate check: fish <- function(d){

Re: [R] Randomly select elements based on criteria

2012-03-22 Thread Jorge I Velez
You could avoid the loop to run for ever by introducing a stop() check. Here is an example using Dr. Savicky's code: # function to sample B pairs of # fishes from different families # -- d has columns fam, born, spawn foo <- function(d, B){ # internal function foo <- function(d){

Re: [R] Randomly select elements based on criteria

2012-03-22 Thread Petr Savicky
On Thu, Mar 22, 2012 at 11:42:53AM -0700, aly wrote: > Hi, > > I want to randomly pick 2 fish born the same day but I need those > individuals to be from different families. My table includes 1787 fish > distributed in 948 families. An example of a subset of fish born in one > specific day would l

[R] Randomly select elements based on criteria

2012-03-22 Thread aly
Hi, I want to randomly pick 2 fish born the same day but I need those individuals to be from different families. My table includes 1787 fish distributed in 948 families. An example of a subset of fish born in one specific day would look like: >fish fam born spawn 25 46 43 25 46