Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing to get single row for each ID's in R

Tags:

r

transpose

EID   Year Performance_rating
E100  2013                  4
E100  2014                  1
E200  2012                  4
E200  2013                  5
E200  2014                  2
E200  2015                  4

The way i need the data for the modeling purpose is non duplicated EID with there performance rating for each year in separate columns (Note some have 2 years of data and some 3 and some 4 based on there joining date)

EID Performance_rating_2012 Performance_rating_2013 Performance_rating_2014 Performance_rating_2015
E100                     NA                       4                       1                      NA
E200                      4                       5                       2                       4 

I tried multiple methods solving this but failed so posting here ,any answers would be much appreciated

like image 449
Sandeep Shetty Avatar asked Dec 28 '25 20:12

Sandeep Shetty


1 Answers

The package tidyr has the exact solution needed for this situation and others:

library(tidyr)
df %>% spread(Year, Performance_rating)

Resulting output is the wide data frame:

   EID 2012 2013 2014 2015
1 E100   NA    4    1   NA
2 E200    4    5    2    4
like image 99
Gopala Avatar answered Dec 31 '25 13:12

Gopala