Richard.Cotton at hsl.gov.uk
2007-Nov-28 14:31 UTC
[R] Antwort: Re: Order observations in a dataframe
> >How > >can > >> I re-label the groups in the descending order of their cumulative > >"weight",> >foo = data.frame(country=c("bul", "cze", "grc", "hun", "prt", "rom", > >"fra", "ita", "gbr", "aut", "bel"), > >weight=c(10,12,12,12,12,4,29,29,29,10,12), > >group=c(1,1,1,1,1,1,2,2,2,3,3)) > > > >#Find the cumulative weights by group > >cumweights = with(foo, tapply(weight, group, sum) > > > >#Incorporate the weights into the data frame > >foo$cumweights = numeric(nrow(foo)) > >for(i in 1:nrow(foo)) foo$cumweights[i] > >cumweights[as.character(foo$group[i])==names(cumweights)] > > > >#Sort by cumweight > >ooo = with(foo, order(cumweights, country, decreasing=TRUE)) > >foo = foo[ooo,]> Thanks Richard, > > but how do you renumerate the group variable accordingly?Try this: sizeofgroups = summary(as.factor(foo$group)) orderofgroups = order(cumweights, decreasing=TRUE) foo$newgroup = rep(orderofgroups, times=sizeofgroups) Regards, Richie. Mathematical Sciences Unit HSL ------------------------------------------------------------------------ ATTENTION: This message contains privileged and confidential inform...{{dropped:20}}