Misha
Misha

Reputation: 3126

Going from multiple dummy variables to a single variable

How can I take n dummy variables that are mutually exclusive in a data frame and concatenate them into a single variable? In the following example

k <- data.frame(H=sample(c(T, F), 100, T))
ifelse(k$H==T, F, sample(c(T, F))) -> k$k
k$u <- ifelse(k$H==T | k$k==T, F, T)

is there an easy method of converting these into one variable i with levels H, k or u?

I guess you could do it with ifelse etc., in this example, but in my data file I have several hundred dummies and I´m too lazy to do this manually.

Upvotes: 2

Views: 509

Answers (1)

kohske
kohske

Reputation: 66842

k$i <- names(k)[apply(k, 1, which)]

will convert bool into one dummy variable.

Upvotes: 6

Related Questions