Hello Susers,
yesterday I posted the following message regarding the default ordering of
factors in S+.
<Hello everyone,
< I am a statistician working in an actuarian group, I mostly develop
GLM's
<for them and they like to pick their own reference level in each factor
<rather than having Splus pick it for them. By default Splus will pick the
<first level in the alphabetically sorted list of levels. My question is
<how do we change this default behaviour or if this is not possible how to
<change the default ordering of factor levels. I know how to do this
<manually, but since I have a whole bunch to do with a lot of levels and
<most likely I'll have to do it often I would like to have a function do it
<for me. Here is a little example of what I'd like to automate.
<
<> ttt.age
<[1] 19 20 30 30 19 20 20 19 19
<> levels(ttt.age)
<[1] "19" "30" "20"
<> table(ttt.age)
< 19 30 20
< 4 2 3
<> levels(ttt.age)_list('30'='30','20'='20','19'='19')
<> levels(ttt.age)
<[1] "30" "20" "19"
<> table(ttt.age)
< 30 20 19
< 2 3 4
<> ttt.age
<[1] 19 20 30 30 19 20 20 19 19
<
<ttt.age have not been changed, but now if it was an explanatory variable
in
< a data.frame Splus would use level "30" as the reference
<rather than the default level "19".
Thanks to all who responded. Bert Gunter and Nick Ellis suggested using
the S+ "ordered" function to order the levels of the factors the way I
wanted them. Victor Moreno and Brad Biggerstaff suggested using Brian
Ripley's function "relevel" which I ended up doing. It worked fine. Here
it is.
x : is the factor for which we want to change the reference level
ref : is either the character name of the new reference level or its index
in "levels(x)"
relevel <- function(x, ref, ...) UseMethod("relevel")
relevel.default <- function(x, ref, ...) stop("relevel only for factors")
relevel.ordered <- function(x, ref, ...) stop("relevel only for factors")
relevel.factor <- function(x, ref, ...)
{
lev <- levels(x); nlev <- length(lev)
if(is.character(ref)) ref <- match(ref, lev)
if(is.na(ref)) stop("ref must be an existing level")
if(ref < 1 || ref > nlev) stop(paste("ref =", ref, "must be in 1 :",
nlev))
factor(x, levels = lev[c(ref, seq(along=lev)[-ref])] )
}
Thanks again,
Gérald Jean
Analyste-conseil (statistiques), Actuariat
télephone : (418) 835-8839
télecopieur : (418) 835-5865
courrier électronique: gerald.jean@spgdag.ca
"In God we trust all others must bring data"
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news
|