Reputation: 8986
I have data collected from a survey. One factor variable is like this:
Column1 Column2 Column3 Column4 Column5
A B C
B C
A B C D E
A C E
C E
B D E
In other words, classes are spread in many different variables. I want to create one binary variable (1 or 0) for each class (A, B, C, D, E). However it's not clear to me how to do it. How can I do it?
EDIT
The output would be something like this:
A B C D E
1 1 1 0 0
0 1 1 0 0
1 1 1 1 1
1 0 1 0 1
0 0 1 0 1
0 1 0 1 1
Upvotes: 3
Views: 210
Reputation: 48211
> data <- data.frame(Column1=c("A","B","A"),Column2=c("B","A","A"))
> data
Column1 Column2
1 A B
2 B A
3 A A
> f <- unique(unlist(data))
> tb <- data.frame(sapply(f, function(x) (rowSums(data == as.character(x)) != 0)*1))
> names(tb) <- f
> tb
A B
1 1 1
2 1 1
3 1 0
Upvotes: 5