reshape 从宽到长,简单 data.table 问题

reshape from wide to long, simple data.table issue

我知道肯定有一个 data.table 的解决方案,可能是 dcast,但我想不通。

我有这样的数据:

library(data.table)
data1 <- data.table(
  id = seq(1:5),
  code = c("A","A","B","A","B"),
  date = as.Date( c("2021-08-11","2021-01-05","2021-02-18","2021-02-13","2021-12-13" ))
)
data2 <- data.table(
  id = seq(1:5),
  code = c("B","B","A","B","A"),
  date = as.Date( c("2021-08-13","2021-01-05","2021-02-19","2021-02-14","2021-12-13" ))
)
data3 <- rbind(data1, data2)

我只是想重塑成这样的宽幅面

data_want <- data.table(
  id = seq(1:5),
  code1 = c("A", "A","B","A","B"),
  data1 = c("2021-08-11", "2021-01-05","2021-02-18","2021-02-13","2021-12-13"),
  code2 = c("B", "B","A","B","A"),
  data2 = c("2021-08-13", "2021-01-05","2021-02-19","2021-02-14","2021-12-13")
)

如何使用dcast

# load package
library(data.table)

# create batch number
data3[, batch := 1:.N, id]

# long to wide
data4 <- dcast(data3
                , id ~ batch
                , value.var = c('code', 'date')
                ); data4

   id code_1 code_2     date_1     date_2
1:  1      A      B 2021-08-11 2021-08-13
2:  2      A      B 2021-01-05 2021-01-05
3:  3      B      A 2021-02-18 2021-02-19
4:  4      A      B 2021-02-13 2021-02-14
5:  5      B      A 2021-12-13 2021-12-13

您还可以按如下方式使用 rowid

dcast(data3, id ~ rowid(id), value.var = c("code", "date"))
#   id code_1 code_2     date_1     date_2
#1:  1      A      B 2021-08-11 2021-08-13
#2:  2      A      B 2021-01-05 2021-01-05
#3:  3      B      A 2021-02-18 2021-02-19
#4:  4      A      B 2021-02-13 2021-02-14
#5:  5      B      A 2021-12-13 2021-12-13