# [R] constructing specially ordered factor

Petr Pikal petr.pikal at precheza.cz
Mon Oct 4 13:05:04 CEST 2004

```
On 4 Oct 2004 at 12:01, Khamenia, Valery wrote:

> Hi all,
>
> my colleagues deal with tables, where every factor is
> represented in two columns. The first column contains some
> numeric codes and the second contains the corresponding
> symbolic name. For example:
>
> ISEX	SSEX
> 0	Female
> 1	Male
> 0	Female
> 0	Female
> ...
>
> another example:
>
> ICONC	SCONC
> 10	Normal
> 1000	ExtraHigh
> 10	Normal
> 0	Nothing
> 100	High
> ...
>
> Colleagues require that the ordering should be done
> always by numeric column and not by the column with
> symbolic equivalents.
>
> Here comes the question:
>
> Is it possible to create factor with properly ordered and
> labeled values in nicer form then in the following long
> solution:
>
>   Factor<-function(Names,Weights) {
>     iunique = !duplicated(Weights)
>     uniqueWeights = Weights[iunique]
>     uniqueNames = Names[iunique] # corresponding unique names
>     factor(Names, uniqueNames[order(uniqueWeights)])
>   }
>
>   Factor(SSEX, ISEX)
>
>   Factor(SCONC, ICONC)

Hallo

Is that what you want?

> ooo<-order(levels(factor(pokus\$ICONC)), decreasing=T)
> my.order<-levels(factor(pokus\$SCONC))[ooo]
> factor(pokus\$SCONC, levels=my.order)
[1] Normal    ExtraHigh Normal    Nothing   High
Levels: Nothing Normal High ExtraHigh

If you want it in a function

Factor <- function(f,n, decreasing=TRUE, ...) {
ooo<-order(levels(factor(n)), decreasing=decreasing)
my.order<-levels(factor(f))[ooo]
factor(f, levels=my.order)
}

Cheers
Petr

>
> Valery.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help