[Rd] factor(x, exclude=y) if x is a factor

Suharto Anggono Suharto Anggono suharto_anggono at yahoo.com
Mon Dec 10 08:46:13 CET 2012

After searching, I see that https://stat.ethz.ch/pipermail/r-help/2011-April/276274.html has mentioned this issue, perhaps more clearly.

Thanks for pointing out "Arguments" section about 'exclude'. That documents the code
    exclude <- as.vector(exclude, typeof(x))

A note: if x is a factor, factor(x, exclude=y) doesn't always do nothing other than dropping unused levels.

> x <- 2:3
> x
[1] 2 3
> xf <- factor(x, levels=x)
> xf
[1] 2 3
Levels: 2 3
> factor(xf, exclude=2)
[1] <NA> 3
Levels: 3

> x <- c(2:3, "a")
> x
[1] "2" "3" "a"
> xf <- factor(x, levels=x)
> xf
[1] 2 3 a
Levels: 2 3 a
> factor(xf, exclude=2)
[1] <NA> 3    a
Levels: 3 a

> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)

[1] LC_COLLATE=English_United States.1252
[2] LC_CTYPE=English_United States.1252
[3] LC_MONETARY=English_United States.1252
[5] LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

--- On Thu, 6/12/12, Lorenz, David <lorenz at usgs.gov> wrote:

From: Lorenz, David <lorenz at usgs.gov>
Subject: Re: [Rd] factor(x, exclude=y) if x is a factor
To: "Suharto Anggono Suharto Anggono" <suharto_anggono at yahoo.com>
Cc: R-devel at r-project.org
Date: Thursday, 6 December, 2012, 10:12 PM

Suharto,  I think that the key is to read the definition of exclude in the Arguments section:a vector of values to be excluded when forming the set of levels. This should 
be of the same type as x, and will be coerced if necessary.  Because the levels already exist for x as a factor, they are not formed or revised, except to drop unused levels in the case where exclude=NULL (or the default value). To drop level a from x use:

factor(as.character(x), exclude="a")  or, on creation:
x <- factor(c("a", "b"), exclude="a")

On Wed, Dec 5, 2012 at 11:39 PM, Suharto Anggono Suharto Anggono <suharto_anggono at yahoo.com> wrote:

factor(x, exclude=factor("a", levels=c("a","b")))

More information about the R-devel mailing list