Hi Alrezq,
The below code should help you. Let me know if you face any issues. Install dplyr and tidyr packages without fail before executing this code.
- In this code, I have also put up a sample data set similar to what you have shared. This section of the code will not be required during the actual implementation. I have enclosed these lines between two comments
#Start and #End. But as requested by @Yarnabrina you need to share a reproducible example for faster turn-around from the experts
- In order to achieve the desired output, we need to first group the data by
shift and then by role and then add the working hours
- Next, to achieve the tabular format we use the
spread function from tidyr package and render the output as a data frame using the data.frame() function
- I have also added a line to export the data to your system (using
write.csv()) assuming you might have to further the output to another team/vertical within the organization for processing
library(dplyr)
library(tidyr)
#Start
shift<-c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
role<-c("Nurse","Nurse","Nurse","Nurse","Nurse","MD","MD","PA","Nurse","Nurse","MD","MD","PA","PA","Nurse","Nurse")
working_hours<-c(3,2,5,7,3,7,2,5,7,3,2,5,7,6,8,3)
DF<-
do.call("cbind",list(shift,role,working_hours)) %>%
data.frame() %>%
rename("shift"="X1","role"="X2","working_hours"="X3") %>%
mutate("working_hours"=as.numeric(working_hours)) %>%
#End
group_by(shift,role) %>%
summarize("total_working_hours"=sum(working_hours,na.rm=TRUE)) %>%
spread(key=role,value=total_working_hours) %>%
ungroup() %>%
data.frame()
print(DF)
write.csv(DF,"working_hours_by_role.csv")
print(paste0("You file was Saved at :: ",getwd()))
Below is how the output of this code looks like:
shift MD Nurse PA
1 1 5 13 NA
2 2 2 7 3
3 3 3 8 9
Warm Regards,
Pritish