[R] Subset and order at the same time?
Berend Hasselman
bhh at xs4all.nl
Sat May 12 20:38:55 CEST 2012
On 12-05-2012, at 20:04, Noah Silverman wrote:
> Is there a way to order data and subset it at the same time??
>
>
>
> I want to sort all the members of group A by their values in column 3. (I'll then do the same for each subsequent group.) This could be done in a loop building up another vector, but I like to avoid loops in R.
> -------------------------------------
> a <- temp[temp$group=="A",]
> a <- a[order(a[,3]),]
> temp[temp$group=="A",] <- a
> ------------------------------------------
>
> Iid like to do this in a single step for each group. However, I can't figure out how to order and subset at the same time.
>
> This *does not work* but should illustrate what I'm trying to do
>
> temp[temp$group=="A",] <- temp[ temp$group=="A" & order(temp[temp$group=="A",3]) , ]
>
>
> Suggestions?
set.seed(413)
temp <- data.frame(group=rep(c("A","B","C"), rep=5), tt=1:15,val=round(runif(15),2), stringsAsFactors=FALSE)
idx <- order(temp$group,temp$val)
# or idx <- order(temp[,1],temp[,3])
idx
z2 <- temp[idx,]
rownames(z2) <- NULL
z2
Possible NA's etc. not taken into account.
Berend
More information about the R-help
mailing list