[R] Recode factor into binary factor-level vars

Dimitris Rizopoulos
Sat, 07 Mar 2009 13:57:32 -0000

one way is:

set.seed(20)
l <- sample(rep.int(c("locA", "locB", "locC",
"locD"), 100), 10, replace=T)

f <- factor(l, levels = paste("loc", LETTERS[1:4], sep =
""))
m <- as.data.frame(model.matrix(~ f - 1))
names(m) <- levels(f)
m


I hope it helps.

Best,
Dimitris


soeren.vogel at eawag.ch wrote:
> How to I "recode" a factor into a binary data frame according to
the
> factor levels:
>
> ### example:start
> set.seed(20)
> l <- sample(rep.int(c("locA", "locB",
"locC", "locD"), 100), 10, replace=T)
> # [1] "locD" "locD" "locD" "locD"
"locB" "locA" "locA" "locA"
"locD" "locA"
> ### example:end
>
> What I want in the end is the following:
>
> m$locA: 0, 0, 0, 0, 0, 1, 1, 1, 0, 1
> m$locB: 0, 0, 0, 0, 1, 0, 0, 0, 0, 0
> m$locC: 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
> m$locD: 1, 1, 1, 1, 0, 0, 0, 0, 1, 0
>
> Instead of 0, NA's would also be fine.
>
> Thanks, S?ren
>

--
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014