[R] Coarsening Factors

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Sep 9 00:26:00 CEST 2005


Murray Jorgensen <maj at waikato.ac.nz> writes:

> It is not uncommon to want to coarsen a factor by grouping levels 
> together. I have found one way to do this in R:
> 
>  > sites
>   [1] F A A D A A B F C F A D E E D C F A E D F C E D E F F D B C
> Levels: A B C D E F
>  > regions <- list(I = c("A","B","C"), II = "D", III = c("E","F"))
>  > library(Epi)
>  > region <- Relevel(sites,regions)
>  > region
>   [1] III I   I   II  I   I   I   III I   III I   II  III III II  I 
> III I   III
> [20] II  III I   III II  III III III II  I   I
> Levels: I II III
> 
> However this seems like using a sledgehammer to crack a nut. Can someone 
> suggest a simpler way to do this task?

Yes,

> regions <- list(I = c("A","B","C"), II = "D", III = c("E","F"))
> levels(sites) <- regions
> sites
 [1] III I   I   II  I   I   I   III I   III I   II  III III II  I III I   III 
[20] II  III I   III II  III III III II  I   I
Levels: I II III


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list