[R] Recode factor into binary factor-level vars

soeren.vogel at eawag.ch
Sat, 07 Mar 2009 13:39:06 -0000

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

--
S?ren Vogel, PhD-Student, Eawag, Dept. SIAM
http://www.eawag.ch, http://sozmod.eawag.ch