Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshape from long to wide and create columns with binary value

Tags:

r

dplyr

tidyr

I am aware of the spread function in the tidyr package but this is something I am unable to achieve. I have a data.frame with 2 columns as defined below. I need to transpose the column Subject into binary columns with 1 and 0.

Below is the data frame:

studentInfo <- data.frame(StudentID = c(1,1,1,2,3,3),
         Subject = c("Maths", "Science", "English", "Maths", "History", "History"))

> studentInfo
  StudentID Subject
1         1   Maths
2         1 Science
3         1 English
4         2   Maths
5         3 History
6         3 History

And the output I am expecting is:

  StudentID Maths Science English History
1         1     1       1       1       0
2         2     1       0       0       0
3         3     0       0       0       1

How can I do this with the spread() function or any other function.

like image 201
sachinv Avatar asked Feb 26 '16 23:02

sachinv


2 Answers

Using reshape2 we can dcast from long to wide.

As you only want a binary outcome we can unique the data first

library(reshape2)

si <- unique(studentInfo)
dcast(si, formula = StudentID ~ Subject, fun.aggregate = length)

#  StudentID English History Maths Science
#1         1       1       0     1       1
#2         2       0       0     1       0
#3         3       0       1     0       0

Another approach using tidyr and dplyr is

library(tidyr)
library(dplyr)

studentInfo %>%
  mutate(yesno = 1) %>%
  distinct %>%
  spread(Subject, yesno, fill = 0)

#  StudentID English History Maths Science
#1         1       1       0     1       1
#2         2       0       0     1       0
#3         3       0       1     0       0

Although I'm not a fan (yet) of tidyr syntax...

like image 92
SymbolixAU Avatar answered Sep 24 '22 05:09

SymbolixAU


We can use table from base R

+(table(studentInfo)!=0)
#            Subject
#StudentID English History Maths Science
 #       1       1       0     1       1
 #       2       0       0     1       0
 #       3       0       1     0       0
like image 30
akrun Avatar answered Sep 25 '22 05:09

akrun