簡體   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