EdWood EdWood - 1 month ago 6
R Question

R make new columns from uniqe values in column dynamically

I want to create new columns based on unique values in one column dynamically. Original:

id, category
1, a
2, b
3, c
4, b


New:

id, category, a, b, c
1, a, 1, 0, 0
2, b, 0, 1, 0
3, c, 0, 0, 1
4, b, 0, 1, 0


For now I do:

data$categoryA = ifelse(data$category=="a", 1, 0)
data$categoryB = ifelse(data$category=="b", 1, 0)
...


But I want to do this dynamically something like this:

for(CATEGORY in unique(data$category) {
data$CATEGORY = ifelse(data$CATEGORY =="a", 1, 0)
}

Answer

I use:

factor2binary=function(inputvar)
{
    set.l <- unique(inputvar)
x=(sapply(set.l, function(x) as.numeric( inputvar == x)))
colnames(x)=unique(inputvar)
x
}


A=sample(LETTERS[1:4],100,rep=T
factor2binary(A)

     D A C B
[1,] 1 0 0 0
[2,] 1 0 0 0
[3,] 0 1 0 0
[4,] 1 0 0 0
[5,] 0 0 1 0
[6,] 0 1 0 0
      ...