[R] extracting half the rows with unique values from data.frame

Nicolas Gutierrez nicolasg at uw.edu
Thu Mar 10 00:45:32 CET 2011


hey!!
Another data.frame question:

I have the following data.frame (pop)

pp=textConnection("
+      xloc yloc  gonad  ind    Ene    W   Agent
+ 1    23  20   516.74   1     0.02 20.21 0.25
+ 2    23  20  1143.20   1     0.02 20.21 0.50
+ 3    23  20   250.00   1     0.02 20.21 0.25
+ 4    22  15   251.98   1     0.02 18.69 0.25
+ 5    24  18   598.08   1     0.02 18.69 0.25
+ 6    24  18   598.08   1     0.02 18.69 0.25
+ 7    22  17   598.08   1     0.02 18.69 0.25
+ 8    23  19   598.08   1     0.02 18.69 0.25
+ 9    21  18   598.08   1     0.02 18.69 0.25
+ 10   25  15   598.08   1     0.02 18.69 0.25
+ ")

pop <- read.table(pp, header = TRUE)
close(pp)

And I need to extract only 50% of the rows within same (xloc,yloc) until 
I reach a number (n=4) of unique (xloc,yloc). For example:

1. If I need n=4, I will extract those rows that unique (xloc,yloc) sum 
up 4. That would be rows 1 to 7.

2. However I need only need half (or rounded to half) the rows in unique 
(loc,yloc).That means from (xloc=23, yloc=20) I will extract only rows 1 
and 2 (n=1); then I will extract row 3 (22,15) to get n=2; then I will 
extract row 4 (22,15) to get n=3; and finally extract row 5 (24,18) to 
get n=4. This would get me the following data.frame with 5 rows instead 
of 7 rows:

       xloc yloc  gonad  ind    Ene    W   Agent
  1    23  20   516.74   1     0.02 20.21 0.25
  2    23  20  1143.20   1     0.02 20.21 0.50
  3    22  15   251.98   1     0.02 18.69 0.25
  4    24  18   598.08   1     0.02 18.69 0.25
  5    22  17   598.08   1     0.02 18.69 0.25

Hope I'm not too confusing.. and THANKS for any help!

Nico



More information about the R-help mailing list