Search code examples
rreshape2dcast

Reshaping data in R with multiple variable levels - "aggregate function missing" warning


I'm trying to use dcast in reshape2 to transform a data frame from long to wide format. The data is hospital visit dates and a list of diagnoses. (Dx.num lists the sequence of diagnoses in a single visit. If the same patient returns, this variable starts over and the primary diagnosis for the new visit starts at 1.) I would like there to be one row per individual (id). The data structure is:

id  visit.date  visit.id    bill.num    dx.code FY  Dx.num  
1   1/2/12      203         1234        409    2012  1      
1   3/4/12      506         4567        512    2013  1      
2   5/6/18      222         3452        488    2018  1      
2   5/6/18      222         3452        122    2018  2      
3   2/9/14      567         6798        923    2014  1 

I'm imagining I would end up with columns like this:

id, date_visit1, date_visit2, visit.id_visit1, visit.id_visit2,  bill.num_visit1, bill.num_visit2, dx.code_visit1_dx1, dx.code_visit1_dx2   dx.code_visit2_dx1, FY_visit1_dx1, FY_visit1_dx2, FY_visit2_dx1

Originally, I tried creating a visit_dx column like this one:

**visit.dx** 
v1dx1 (visit 1, dx 1)
v2dx1 (visit 2, dx 1)
v1dx1 (...)
v1dx2
v1dx1

And used the following code, omitting "Dx.num" from the DF, as it's accounted for in "visit.dx":

    wide <-
    dcast(
    setDT(long),
    id + visit.date + visit.id + bill.num ~ visit.dx,
    value.var = c(
      "dx.code",
      "FY"
    )
  )

When I run this, I get the warning "Aggregate function missing, defaulting to 'length'" and new dataframe full of 0's and 1's. There are no duplicate rows in the dataframe, however. I'm beginning to think I should go about this completely differently.

Any help would be much appreciated.


Solution

  • The data.table package extended dcast with rowid and allowing multiple value.var, so...

    library(data.table)
    dcast(setDT(DF), id ~ rowid(id), value.var=setdiff(names(DF), "id"))
    
       id visit.date_1 visit.date_2 visit.id_1 visit.id_2 bill.num_1 bill.num_2 dx.code_1 dx.code_2 FY_1 FY_2 Dx.num_1 Dx.num_2
    1:  1       1/2/12       3/4/12        203        506       1234       4567       409       512 2012 2013        1        1
    2:  2       5/6/18       5/6/18        222        222       3452       3452       488       122 2018 2018        1        2
    3:  3       2/9/14         <NA>        567         NA       6798         NA       923        NA 2014   NA        1       NA