0

R newbie here. I need to use one of the columns "Student Status" and make it columns and get the date values associated with that StudentID and StudentStatus.

Here is my original data.

Tabular Data

This is my desired output.

enter image description here

Please help. Thanks.

mgh
  • 71
  • 6
  • Does this answer your question? [How to reshape data from long to wide format](https://stackoverflow.com/questions/5890584/how-to-reshape-data-from-long-to-wide-format) – divibisan Jan 21 '20 at 21:50

2 Answers2

1

You can also use the pivot_wider function from tidyr to do that.

library(tidyr)

df %>%
  pivot_wider(names_from = StudentStatus,
              values_from = StatusDate)
  • pivot_wider doesn't appear to work currently, unless you grab a developer version of dplyr, but even then has issues: https://github.com/tidyverse/tidyr/issues/635 – user18139 Jun 22 '21 at 12:00
0

You can use the dcast function from the data.table package to do this ...

# install.packages('data.table')
library(data.table)

# Coerce the data.frame to a data.table.
dt <- data.table(df)

# Cast the data.table ...
dcast(dt, StudentID + City ~ StudentStatus)
#    StudentID           City Dropped Out   Enrolled  Graduated
# 1:         1 Long Beach, CA  12/21/2012  8/21/2011       <NA>
# 2:         2 Long Beach, CA        <NA>  8/21/2011 12/11/2014
# 3:         3 Long Beach, CA        <NA> 11/21/2011  1/21/2016

Example data:

df <- data.frame(StudentID = c(1, 2, 3, 1, 2, 3),
                City = rep("Long Beach, CA", 6), 
                StudentStatus = c("Enrolled", "Enrolled","Enrolled", "Dropped Out", "Graduated", "Graduated"), 
                StatusDate = c("8/21/2011","8/21/2011","11/21/2011","12/21/2012","12/11/2014","1/21/2016"))
Khaynes
  • 1,976
  • 2
  • 15
  • 27