An example of a non-settable function would be labels. You can only set factor labels when they are created with the factor() function. There is no labels<- function. Not that ‘labels’ and ‘levels’ in factors make any sense….
> fac <- factor(1:3, labels=c("one", "two", "three"))
> fac
[1] one two three
Levels: one two three
> labels(fac)
[1] "1" "2" "3"
OK, I asked for labels, which one might assume were as set by the factor call, but I get something quite … what’s the word, unintuitive?
> levels(fac)
[1] "one" "two" "three"
So it appears that setting labels is really setting levels.
> fac <- factor(1:3, levels=c("one", "two", "three"))
> levels(fac)
[1] "one" "two" "three"
OK that is as expected. So what are labels when one sets levels?
> fac <- factor(1:3, levels=c("one", "two", "three"), labels=c("x","y", "z") )
> labels(fac)
[1] "1" "2" "3"
> levels(fac)
[1] "x" "y" "z"
It would seem that ‘labels’ arguments for factor() trump any ‘levels’ arguments for the specification of levels. Why should this be? And why does labels() return what I would have imagined to be retrieved with as.character(as.numeric(fac))?
(This was a tangential comment [labelled as such] in an earlier answer about assignment functions to which I was asked to move to a question. So here’s your opportunity to enlighten me.)
I think the way to think about the difference between
labelsandlevels(ignoring thelabels()function that Tommy describes in his answer) is thatlevelsis intended to tell R which values to look for in the input (x) and what order to use in the levels of the resultingfactorobject, andlabelsis to change the values of the levels after the input has been coded as a factor … as suggested by Tommy’s answer, there is no part of thefactorobject returned byfactor()that is calledlabels… just the levels, which have been adjusted by thelabelsargument … (clear as mud).For example:
Because the first two elements of
xwere not found inlevels, the first two elements offareNA. Because"d"and"e"were included inlevels, they show up in the levels offeven though they did not occur inx.Now with
labels:After R figures out what should be in the factor, it re-codes the levels. One can of course use this to do brain-frying things such as:
Another way to think about
levelsis thatfactor(x,levels=L1,labels=L2)is equivalent toI think an appropriately phrased version of this example might be nice for Pat Burns’s R inferno — there are plenty of factor puzzles in section 8.2, but not this particular one …