Aggregate and reshape from long to wide

Your data are already in a long format that can be used easily by “reshape2”, like this:

library(reshape)
dcast(df, bdate ~ sex + age + diag, value.var = "admissions")
#        bdate Female_35-64_card Female_35-64_cere Female_65-74_card Female_65-74_cere
# 1 1987-01-01                 1                 6                 1                 6
# 2 1987-01-02                 4                 4                 0                 6
# 3 1987-01-03                 2                 6                 4                 5
#   Male_35-64_card Male_35-64_cere Male_65-74_card Male_65-74_cere
# 1               0               6               0               1
# 2               0               5               0               2
# 3               1               6               0               4

I don’t see any aggregation in your sample output, but if aggregation is required, you can achieve this with the fun.aggregate function within dcast.

Leave a Comment