簡體   English   中英

如何基於data.table中的其他列創建索引列?

[英]How to create an indexed column based in other columns in a data.table?

我有一個data.table DF如下。 第三位是當時擁有控球權的球隊(以分鍾和秒為單位)。

    minute second    teamId   isGoal     
 1:     10     22 Atletico MG      0
 2:     10     26 Atletico MG      0
 3:     10     30 Atletico MG      0
 4:     10     33 Atletico MG      0
 5:     10     35 Atletico MG      0
 6:     10     37 Atletico MG      0
 7:     10     38 Atletico MG      1
 8:     10     40 Atletico GO      0
 9:     10     42 Atletico GO      0
10:     10     48 Atletico GO      1
11:     10     51 Atletico MG      0
12:     10     54 Atletico MG      1
13:     10     60 Atletico MG      0

我想創建兩個新的列。 每個人加總每個團隊的目標數。 例如,輸出應為:

        minute second    teamId   isGoal  AtleticoMG AtleticoGO    
 1:     10     22 Atletico MG      0               0          0
 2:     10     26 Atletico MG      0               0          0
 3:     10     30 Atletico MG      0               0          0
 4:     10     33 Atletico MG      0               0          0
 5:     10     35 Atletico MG      0               0          0
 6:     10     37 Atletico MG      0               0          0
 7:     10     38 Atletico MG      1               1          0
 8:     10     40 Atletico GO      0               1          0
 9:     10     42 Atletico GO      0               1          0
10:     10     48 Atletico GO      1               1          1
11:     10     51 Atletico MG      0               1          1
11:     10     51 Atletico MG      0               1          1
12:     10     54 Atletico MG      1               2          1
13:     10     60 Atletico MG      0               2          1

想要避免for循環。 我敢肯定在data.table中一定很容易做到,但是怎么辦呢?

這是一個使用dplyr和“玩具”示例的解決方案,該示例類似於您在開頭的文章中給出的數據框。

基本上,基本上,您需要為每個團隊創建一列指標,如果該團隊在數據框的特定行中進球,則該指標為1。 然后,您可以使用cumsum()函數在這些新生成的列中進行累加。

library(dplyr)
x <- data.frame( teamID=c('A', 'A', 'B', 'A', 'A', 'B', 'B', 'B', 'A'),
                 isGoal=c(0,0,1,0,1,0,0,1, 0) ) %>%
mutate( AGoal = cumsum( isGoal*(teamID=='A') ),
        BGoal = cumsum( isGoal*(teamID=='B') ) )

輸出:

teamID isGoal AGoal BGoal
A      0      0     0
A      0      0     0
B      1      0     1
A      0      0     1
A      1      1     1
B      0      1     1
B      0      1     1
B      1      1     2
A      0      1     2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM