R: Column Disappears in the "acast()" Command

I have the following data frame (called "graph_data"):

> graph_data
     dates types count
1  2010-01     A   171
2  2010-01     B   146
3  2010-01     C    55
4  2010-01     D    71
5  2010-01     E    66
6  2010-02     A    78
7  2010-02     B    56
8  2010-02     C    23
9  2010-02     D    21
10 2010-02     E    30
11 2010-03     A    43
12 2010-03     B    21
13 2010-03     C    18
14 2010-03     D    11

Using the "reshape2" library, I was able to change this data into "long format":

dd <- graph_data
final = data.frame(reshape2::acast(dd, list(names(dd)[1], names(dd)[2])))

          A   B  C  D  E
2010-01 171 146 55 71 66
2010-02  78  56 23 21 30
2010-03  43  21 18 11 16
2010-04  32  20  7 14  9
2010-05  36  27  7 10 12

This worked fine - but now the "dates" column has disappeared:

> str(final)
'data.frame':   5 obs. of  5 variables:
 $ A: int  171 78 43 32 36
 $ B: int  146 56 21 20 27
 $ C: int  55 23 18 7 7
 $ D: int  71 21 11 14 10
 $ E: int  66 30 16 9 12

enter image description here

Is it possible to bring the "dates" column back? (i.e. 6 total columns)

Can someone please show me how to fix this problem?

Thanks!

graph_data <- read.csv("~/R/Play/Dummy.csv")
head(graph_data)
#>     dates types count
#> 1 2010-01     A   171
#> 2 2010-01     B   146
#> 3 2010-01     C    55
#> 4 2010-01     D    71
#> 5 2010-01     E    66
#> 6 2010-02     A    78
reshape2::dcast(data = graph_data,formula = dates~types, #acast also works
                value.var = "count")
#>     dates   A   B  C  D  E
#> 1 2010-01 171 146 55 71 66
#> 2 2010-02  78  56 23 21 30
#> 3 2010-03  43  21 18 11 NA

Created on 2022-01-18 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.