gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:59:18 27 4
gpt4 key购买 nike

我知道必须有一个单行 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)

我只是想 reshape 成这样的宽幅

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 实现?

最佳答案

你也可以像下面这样使用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

关于reshape 从宽到长,简单的 data.table 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71047497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com