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