繁体   English   中英

在R中的`data.table`中,是否有一种方法可以基于索引将值快速分配给行?

[英]In `data.table` in R, is there a way to fast-assign values to rows based on an index?

我目前正在使用一个大约有2亿行的data.table表。

>table
user     age
A        19
B        22
C        18
D        13
E        93
F        15
G        11
H        16
I        33
J        25
K        44
L        23
M        76
N        34
O        18
P        32
Q        55

另外,我有一个“索引”表,看起来像:

> index
row_number     count
1              5
3              7
7              12
8              100
12             3
14             4

我的目标是能够将count列追加到table row_number列表示table的行号。 因此,当row_number等于1时,我们将值5附加到用户A且年龄为table 19行。 对于row_number等于3,我们向用户C和年龄18插入值7。两者之间存在间隙,因此我想用0填充它们。

所以总的来说,我想:

>table
user     age    count 
A        19     5
B        22     0
C        18     7
D        13     0
E        93     0
F        15     0
G        11     12
H        16     100
I        33     0
J        25     0
K        44     0
L        23     3
M        76     0
N        34     4
O        18     0
P        32     0
Q        55     0

到目前为止,我执行此操作的代码是:

table[,count:= count, by=.N]

但是,我无法获得正确的排序。 有谁知道我如何在data.table完成此data.table 谢谢!

这是使用set的方法

# set everything to 0
set(table, j = 'count', value = 0)
# replace the appropriate indices with the relevant values
set(table, j = 'count', i = index[['rownumber']], j = index[['count']])

您也可以使用:=运算符。 您不需要by这里。 相反,您可以这样做:

table[, count := 0L][index$row_number, count := index$count]

首先,我们初始化count与整数值0 ,然后在给定的行号i ,我们修改 counttable 就地用相应的count从值index

高温超导

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM