What is the least surprising way of initializing a factor with predefined levels and with length 0? as.factor(c("eins", "zwei", "drei"))[FALSE] does the job but looks a bit weird. -- Johannes H?sing There is something fascinating about science. One gets such wholesale returns of conjecture mailto:johannes at huesing.name from such a trifling investment of fact. http://derwisch.wikidot.com (Mark Twain, "Life on the Mississippi")
On Sun, 2008-07-13 at 18:47 +0200, Johannes Huesing wrote:> What is the least surprising way of initializing a factor with > predefined levels and with length 0? > as.factor(c("eins", "zwei", "drei"))[FALSE] > does the job but looks a bit weird. >Notice that one does not need to specify any data as argument 'x' to factor() because, by default, x = character(). Therefore, we need only specify the levels we want:> factor(levels = c("one","two","three"))factor(0) Levels: one two three HTH G
Gavin Simpson <gavin.simpson at ucl.ac.uk> [Sun, Jul 13, 2008 at 08:18:37PM CEST]:> On Sun, 2008-07-13 at 18:47 +0200, Johannes Huesing wrote:[...]> > as.factor(c("eins", "zwei", "drei"))[FALSE] > > does the job but looks a bit weird. > >[...]> > factor(levels = c("one","two","three")) > factor(0) > Levels: one two threeAh, ok, I was unaware of factor(), only knew as.factor(). Many thanks Johannes -- Johannes H?sing There is something fascinating about science. One gets such wholesale returns of conjecture mailto:johannes at huesing.name from such a trifling investment of fact. http://derwisch.wikidot.com (Mark Twain, "Life on the Mississippi")
I have found that factor vectors are shy beasts. Consider:> empty <- factor(levels=c("eins", "zwei")) > value <- factor("eins", levels=c("eins", "zwei")) > c(empty, value)[1] 1> empty[1] <- value > empty[1] eins Levels: eins zwei>I could not exactly predict this behaviour, but ?c says: The output type is determined from the highest type of the components in the hierarchy NULL < raw < logical < integer < real < complex < character < list < expression. As factor is a class (of the whole vector) and not a type (of a single element), c does not seem to preserve the object information, i.e. there does not seem to be a c.factor, correct? -- Johannes H?sing There is something fascinating about science. One gets such wholesale returns of conjecture mailto:johannes at huesing.name from such a trifling investment of fact. http://derwisch.wikidot.com (Mark Twain, "Life on the Mississippi")