gpt4 book ai didi

r - 我在 data.table 中复制行的方法有效吗?

转载 作者:行者123 更新时间:2023-12-03 02:50:26 24 4
gpt4 key购买 nike

我在一个 data.table 中有每月数据,在另一个 data.table 中有年度数据,现在我想将年度数据与每月中的相应观察结果进行匹配数据。

我的做法是:复制每个月的年度数据,然后将月度和年度数据连接起来。现在我有一个关于行重复的问题。我知道该怎么做,但我不确定这是否是最好的方法,所以一些意见会很好。

这是我的年度数据的示例 data.table DT 以及我当前的复制方式:

library(data.table)
DT <- data.table(ID = paste(rep(c("a", "b"), each=3), c(1:3, 1:3), sep="_"),
values = 10:15,
startMonth = seq(from=1, by=2, length=6),
endMonth = seq(from=3, by=3, length=6))
DT
ID values startMonth endMonth
[1,] a_1 10 1 3
[2,] a_2 11 3 6
[3,] a_3 12 5 9
[4,] b_1 13 7 12
[5,] b_2 14 9 15
[6,] b_3 15 11 18
#1. Alternative
DT1 <- DT[, list(MONTH=startMonth:endMonth), by="ID"]
setkey(DT, ID)
setkey(DT1, ID)
DT1[DT]
ID MONTH values startMonth endMonth
a_1 1 10 1 3
a_1 2 10 1 3
a_1 3 10 1 3
a_2 3 11 3 6
[...]

最后的连接正是我想要的。但是,DT[, list(MONTH=startMonth:endMonth), by="ID"] 已经完成了我想要的一切,除了将其他列添加到 DT 中,所以我想知道我是否可以删除代码中的最后三行,即 setkeyjoin 操作。事实证明,您只需执行以下操作即可:

#2. Alternative: More intuitiv and just one line of code
DT[, list(MONTH=startMonth:endMonth, values, startMonth, endMonth), by="ID"]
ID MONTH values startMonth endMonth
a_1 1 10 1 3
a_1 2 10 1 3
a_1 3 10 1 3
a_2 3 11 3 6
...

但是,这仅起作用,因为我将列名称硬编码到 list 表达式中。在我的真实数据中,我事先不知道所有列的名称,所以我想知道是否可以告诉 data.table 返回我的列 MONTH如上所示计算 DT 的所有其他列。 .SD 似乎能够做到这一点,但是:

DT[, list(MONTH=startMonth:endMonth, .SD), by="ID"]
Error in `[.data.table`(DT, , list(YEAR = startMonth:endMonth, .SD), by = "ID") :
maxn (4) is not exact multiple of this j column's length (3)

总而言之,我知道它是如何完成的,但我只是想知道这是否是最好的方法,因为我仍然在 data.table 的语法上遇到了一些困难>并且经常在帖子和维基上读到做事的方式有好有坏。另外,我不太明白为什么在使用 .SD 时出现错误。我认为这只是告诉 data.table 您想要所有列的任何简单方法。我错过了什么?

最佳答案

看到这个,我意识到答案是可能的,因为 ID 是一个唯一的键(没有重复项)。这是另一个重复的答案。但是,顺便说一句,一些 NA 似乎悄然出现。这可能是一个错误吗?我正在使用 v1.8.7(提交 796)。

library(data.table)
DT <- data.table(x=c(1,1,1,1,2,2,3),y=c(1,1,2,3,1,1,2))

DT[,rep:=1L][c(2,7),rep:=c(2L,3L)] # duplicate row 2 and triple row 7
DT[,num:=1:.N] # to group each row by itself

DT
x y rep num
1: 1 1 1 1
2: 1 1 2 2
3: 1 2 1 3
4: 1 3 1 4
5: 2 1 1 5
6: 2 1 1 6
7: 3 2 3 7

DT[,cbind(.SD,dup=1:rep),by="num"]
num x y rep dup
1: 1 1 1 1 1
2: 2 1 1 1 NA # why these NA?
3: 2 1 1 2 NA
4: 3 1 2 1 1
5: 4 1 3 1 1
6: 5 2 1 1 1
7: 6 2 1 1 1
8: 7 3 2 3 1
9: 7 3 2 3 2
10: 7 3 2 3 3
<小时/>

为了完整起见,一种更快的方法是rep行号,然后一步获取子集(不分组,也不使用cbind .SD) :

DT[rep(num,rep)]
x y rep num
1: 1 1 1 1
2: 1 1 2 2
3: 1 1 2 2
4: 1 2 1 3
5: 1 3 1 4
6: 2 1 1 5
7: 2 1 1 6
8: 3 2 3 7
9: 3 2 3 7
10: 3 2 3 7

在此示例数据中,rep 列恰好与 rep() 基函数同名。

关于r - 我在 data.table 中复制行的方法有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8009900/

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