user9292
user9292

Reputation: 1145

Reshape a data frame into a wide shape

The data contains two variables: id and grade. Each id can have multiple records for each grade.

dat <- data.frame(id = c(1,1,1,2,2,2,2,3,3,4,5,5,5),
                  grade = c("a", "b", "c", "a", "a", "b", "b", "d", "f", "c", "a", "e", "f"))

I want to reshape the data into a wide shape such that each id has only one record and each unique grade becomes a single column. The value of each column is either 0 or 1, depending on the grades for each id.

The final data set looks like:

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

I tried this, but no luck.

  n.dat <- reshape(dat, timevar = "grade",idvar = c("id"),direction = "wide") 

Upvotes: 2

Views: 147

Answers (1)

David Arenburg
David Arenburg

Reputation: 92282

You could simply table the values, then convert to logical based on > 0 condition and then convert back to numeric using the + unary operator (or if you want less golfed, by simply + 0)

+(table(dat) > 0)
#     grade
# id  a b c d e f
#   1 1 1 1 0 0 0
#   2 1 1 0 0 0 0
#   3 0 0 0 1 0 1
#   4 0 0 1 0 0 0
#   5 1 0 0 0 1 1

Upvotes: 6

Related Questions