Timothée HENRY
Timothée HENRY

Reputation: 14604

R transform data frame to have one columns as rows

I have a data frame:

dput(x)
structure(list(ymd = structure(c(1446336000, 1446336000, 1446336000, 
1446336000, 1446336000, 1446336000, 1446336000, 1446336000, 1446422400, 
1446422400, 1446422400, 1446422400, 1446422400, 1446422400, 1446422400, 
1446422400, 1446508800, 1446508800, 1446508800, 1446508800, 1446508800, 
1446508800, 1446508800, 1446508800), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), id = c(2, 9, 13, 15, 20, 24, 27, 41, 2, 9, 
13, 15, 20, 24, 27, 41, 2, 9, 13, 15, 20, 24, 27, 41), value = c(2865, 
3015, 4365, 6015, 4515, 1815, 765, 5115, 2865, 3015, 5565, 6015, 
4515, 1815, 765, 4965, 2865, 3015, 5565, 6015, 4515, 1815, 765, 
2715)), .Names = c("ymd", "id", "value"), row.names = c(NA, 24L
), class = "data.frame")

> x
          ymd id value
1  2015-11-01  2  2865
2  2015-11-01  9  3015
3  2015-11-01 13  4365
4  2015-11-01 15  6015
5  2015-11-01 20  4515
6  2015-11-01 24  1815
7  2015-11-01 27   765
8  2015-11-01 41  5115
9  2015-11-02  2  2865
10 2015-11-02  9  3015
11 2015-11-02 13  5565
12 2015-11-02 15  6015
13 2015-11-02 20  4515
14 2015-11-02 24  1815
15 2015-11-02 27   765
16 2015-11-02 41  4965
17 2015-11-03  2  2865
18 2015-11-03  9  3015
19 2015-11-03 13  5565
20 2015-11-03 15  6015
21 2015-11-03 20  4515
22 2015-11-03 24  1815
23 2015-11-03 27   765
24 2015-11-03 41  2715

and would like to obtain a table showing the values for each id, over time. So rows are the id's, and columns are the dates (ymd). And the cell values would be the values.

I would look like this:

id 2015-11-01 2015-11-02 2015-11-03
 2       2865       2865       2865
 9       3015       3015       3015
13       4365       ... 
...

I tried playing with reshape cast, but could not figure it out.

Upvotes: 0

Views: 33

Answers (1)

Ven Yao
Ven Yao

Reputation: 3710

library(reshape2)  
dcast(x, id~ymd)
#   id 2015-11-01 2015-11-02 2015-11-03
# 1  2       2865       2865       2865
# 2  9       3015       3015       3015
# 3 13       4365       5565       5565
# 4 15       6015       6015       6015
# 5 20       4515       4515       4515
# 6 24       1815       1815       1815
# 7 27        765        765        765
# 8 41       5115       4965       2715

Upvotes: 2

Related Questions