[R] Selecting obs within groups defined by 2 variables

Rui Barradas rui1174 at sapo.pt
Wed Apr 4 23:03:33 CEST 2012


Hello,

>
> The by function does not seem to allow two variables in the Indices  
> argument:
> 

Yes it does, but you must use a list of variables.
(Read the help for 'by': INDICES 	a factor or a list of factors, each of
length nrow(data).)

mydata <- read.table(text="
C1 C2 C3
1 x 1
1 x 2
1 y 1
1 y 2
2 x 1
2 x 2
2 y 1
2 y 2
", header=TRUE)

last <-by(mydata, list(mydata$C1, mydata$C2), tail, n=1)
last

# Another way, output is more usefull.
last2 <- aggregate(mydata, list(mydata$C1, mydata$C2), tail, n=1)
last2[, -(1:2)]

Hope this helps,

Rui Barradas






--
View this message in context: http://r.789695.n4.nabble.com/Selecting-obs-within-groups-defined-by-2-variables-tp4533125p4533169.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list