Search code examples
rdataframedummy-variable

Make dummy variables from multiple columns and create new dataframe


I need to make a dataframe of dummies from survey data where respondents have stated words in several columns in a dataframe. Here is a simplified example to illustrate what I need to do? A single word is here represented by a letter.

id <- c(1:6)
v.1 <- c("a","b","d","e","a","c")
v.2 <- c("b","a","a","a","b","a")
v.3 <- c("e","c","b","b","e","b")

df <- data.frame(id,v.1,v.2,v.3)

> df
  id v.1 v.2 v.3
1  1   a   b   e
2  2   b   a   c
3  3   d   a   b
4  4   e   a   b
5  5   a   b   e
6  6   c   a   b

Here is my wanted output?

> print(df.dummy)
   id  a b c d e
1:   1 1 1 0 0 1
2:   2 1 1 1 0 0
3:   3 1 1 0 1 0
4:   4 1 1 0 0 1
5:   5 1 1 0 0 1
6:   6 1 1 1 0 0

Any ideas?


Solution

  • You can use reshape2:

    library(reshape2)
    dcast( melt(df,id.var="id"), id ~ value, length)
    

    which gives

      id a b c d e
    1  1 1 1 0 0 1
    2  2 1 1 1 0 0
    3  3 1 1 0 1 0
    4  4 1 1 0 0 1
    5  5 1 1 0 0 1
    6  6 1 1 1 0 0
    

    Or use recast to "melt and cast in a single step":

    recast(df, id ~ value, id.var = "id", length)
    

    Without using a package, you could do table( rep(df$id,ncol(df)-1), unlist(df[-1]) ).