0

I have a shift planning data frame containing one rows per day per employee like this:

day<-as.Date(c('2017-04-03','2017-04-04','2017-04-05', '2017-04-06',
    '2017-04-07', '2017-04-08', '2017-04-09', '2017-04-03', 
    '2017-04-04', '2017-04-05', '2017-04-06', '2017-04-07', 
    '2017-04-08', '2017-04-09', '2017-04-03','2017-04-04','2017-04-05', 
    '2017-04-06', '2017-04-07', '2017-04-08', '2017-04-09'))
employee<-c('John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 
          'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 
          'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy')
shift<-as.factor(c('D', 'D', 'N', 'N', 'R', '-', 'D', 'N', 'R', 
             '-', '-', '-', 'N', 'N', '-', '-', '-', 'D', 'D', 'D', '-'))
roster<-data.frame(day, employee, shift)

This is what I am looking for:

employee   03  04  05  06  07  08  09
John Doe    D   D   N   R   -   -   D
Martin Maw  N   R   -   -   -   N   N
Denis Rudy  -   -   -   D   D   D   -

Is there a package which may help me doing such a report like view of the data frame?

How to reshape data from long to wide format?

shows the solution, but giving a different formulation of the question which was hard to find.

Community
  • 1
  • 1
Johann Horvat
  • 1,285
  • 1
  • 14
  • 18

1 Answers1

1

Using tidyr we can spread the data.frame:

library(tidyr)

roster %>% 
    spread(key = day, value = shift) 

##     employee 2017-04-03 2017-04-04 2017-04-05 2017-04-06 2017-04-07
## 1 Denis Rudy          -          -          -          D          D
## 2   John Doe          D          D          N          N          R
## 3 Martin Maw          N          R          -          -          -
##   2017-04-08 2017-04-09
## 1          D          -
## 2          -          D
## 3          N          N

data:

day<-as.Date(c('2017-04-03','2017-04-04','2017-04-05', '2017-04-06', '2017-04-07', '2017-04-08', '2017-04-09', '2017-04-03','2017-04-04','2017-04-05', '2017-04-06', '2017-04-07', '2017-04-08', '2017-04-09', '2017-04-03','2017-04-04','2017-04-05', '2017-04-06', '2017-04-07', '2017-04-08', '2017-04-09'))
employee<-c('John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 'John Doe', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Martin Maw', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy', 'Denis Rudy')
shift<- as.factor(c('D', 'D', 'N', 'N', 'R', '-', 'D', 'N', 'R', '-', '-', '-', 'N', 'N', '-', '-', '-', 'D', 'D', 'D', '-'))
roster<-data.frame(day, employee, shift)
GGamba
  • 13,140
  • 3
  • 38
  • 47