[R] sample {base}

arun smartpink111 at yahoo.com
Wed Jun 5 20:34:58 CEST 2013


Hi,
Try:
 fun1<- function(dat,Col1,Col2,number){
 lst1<- split(dat,list(dat[,Col1],dat[,Col2]))
 lst2<- lst1[lapply(lst1,nrow)>0]
 res<- lapply(lst2,function(x) sample(x[,1],if(nrow(x)< number) nrow(x) else number,replace=FALSE))
 res}
head(fun1(Gpool,"LngtClas","SpCode",5),4)
#$`40_49.MERLMER`
#[1]  34  38 143   3  19
#
#$`50_59.MERLMER`
#[1]  20 112 115 104  77
#
#$`60_69.MERLMER`
#[1] 130 136  40 128  32
#
#$`70_.MERLMER`
#[1] 44 63 96



A.K.



----- Original Message -----
From: Xochitl CORMON <Xochitl.Cormon at ifremer.fr>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, June 5, 2013 10:27 AM
Subject: [R] sample {base}

Hi all,

I'm trying to randomly select sample numbers for length class groups (5 
per length class).

For this I'm using a loop FOR and the function sample () and specified a 
size for the sampling of 5. Unfortunately, one of the length class group 
does not contain 5 individuals. For me is not a big deal as I have 
others groups to complete. However it bothers me that the sampling 
function does not select any individuals in this group generating the 
error below :

Error in sample(Gpool2$SampleNb[Gpool2$LngtClas == LngtClas[[i]] & 
Gpool2$SpCode ==  : can not take a sample larger than the population 
when 'replace = FALSE'.

I understand why this error message appears but I was wondering if there 
is a way to select all the items present in the group even if it's not 5 
(something like size =< 5).

LngtClas <- list( "40_49", "50_59", "60_69", "70_")
SpCode <- list ("POLLVIR ", "MERLMER")

a <- as.character(sample(Gpool$SampleNb[Gpool$LngtClas == LngtClas[[4]] 
& Gpool$SpCode == SpCode[[2]]], size = 5, replace = FALSE))

You can find enclosed my dataset,

Thank you for the help,

Xochitl C.

<>< <>< <>< <><

Xochitl CORMON
+33 (0)3 21 99 56 84

Doctorante en sciences halieutiques
PhD student in fishery sciences

<>< <>< <>< <><

IFREMER
Centre Manche Mer du Nord
150 quai Gambetta
62200 Boulogne-sur-Mer

<>< <>< <>< <><


______________________________________________
R-help at 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.




More information about the R-help mailing list