[R] problem understanding factor levels for use lattice panel order
Rolf Turner
r.turner at auckland.ac.nz
Thu Oct 8 21:54:54 CEST 2009
On 9/10/2009, at 6:52 AM, Folkes, Michael wrote:
> Hello all,
> In order to get the desired order of panels within lattice I
> realized I needed to define my factor levels.
> I now see how to properly do it (attached code), but:
> 1. I don't understand why I have to use factor() on a variable that
> is already a factor, and why levels() alone doesn't work to
> readjust the level order.
> 2. I just noticed that if I do use levels(xx$v1), it's changing
> something that can't be repaired with:
> xx$v1<-factor(xx$v1,levels=c('b','a','c')), and both plots are wrong.
> I'm failing to grasp what levels() is doing compared to factor().
> thanks very much.
> Michael Folkes
>
> #__________________________________
>
> xx<-data.frame(v1=rep(letters[1:3],rep(3,3)),v2=rep(1:3,3),v3=rep
> (1:3,rep(3,3)))
> str(xx)
> levels(xx$v1)
>
> #INCORRECT:
> #if I run this level(), the factor() below doens't work properly
> #levels(xx$v1)<-c('b','a','c')
> xx
> g1<-xyplot(v3~v2|v1,data=xx)
>
> #CORRECT:
> xx$v1<-factor(xx$v1,levels=c('b','a','c'))
> g2<-xyplot(v3~v2|v1,data=xx)
> xx
> print(g1,split=c(1,1,2,1),more=T)
> print(g2,split=c(2,1,2,1),more=F)
The object xx$v1 is ``really'' the vector of indices 1 1 1 2 2 2 3 3 3
Initially it has a levels attribute c('a','b','c') which says to
associate the symbol 'a' with index 1, 'b', with index 2, and 'c'
with index 3.
When you type xx$v1 you see the sequence a a a b b b c c c.
The call
levels(xx$v1) <- c('b','a','c')
says to associate the symbol 'b' with index 1, 'a', with index 2, and
'c' with index 3.
Now when you type xx$v1 you see the sequence b b b a a a c c c.
The call
xx$v1 <- factor(xx$v1,levels=c('b','a','c'))
(done ***instead*** of the the call levels(xx$v1) <- c('b','a','c'))
essentially replaces xx$v1 by match(xx$v1,c('b','a','c')) so that now
xx$v1 is
``really'' the vector of indices 2 2 2 1 1 1 3 3 3. The levels
attribute says
that 'b' is associated with 1, 'a' is associated with 2, and 'c' is
associated with 3.
So when you type xx$v1 you see a a a b b b c c c as before.
cheers,
Rolf Turner
######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
More information about the R-help
mailing list