[R] Antwort: Re: Order observations in a dataframe

Richard.Cotton at hsl.gov.uk Richard.Cotton at hsl.gov.uk
Wed Nov 28 15:31:37 CET 2007


> >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}}



More information about the R-help mailing list