如何在 R 中向 data.table 物件新增一列?


如要向 data.table 物件新增一列,我們可以按照以下步驟操作 -

  • 首先,建立一個 data.table 物件。
  • 使用 := 函式向物件新增一列

建立 data.table 物件

讓我們建立一個 data.table 物件,如下所示 -

library(data.table)
x<-rpois(20,5)
y<-rpois(20,1)
DT<-data.table(x,y)
DT

執行上面這個指令碼,它將生成以下輸出(此輸出將在你的系統上有所不同,原因是隨機化) -

   x y
1: 5 1
2: 4 0
3: 4 0
4: 7 2
5: 2 2
6: 6 0
7: 3 0
8: 7 3
9: 4 0
10: 4 1
11: 6 3
12: 4 1
13: 4 0
14: 6 0
15: 5 1
16: 5 5
17: 9 0
18: 5 2
19: 5 1
20: 5 1

向 data.table 物件新增一列

使用 := 函式向 DT 新增一列 -

library(data.table)
x<-rpois(20,5)
y<-rpois(20,1)
DT<-data.table(x,y)
DT[,z:=rpois(20,2)]
DT

輸出

   x y z
1: 5 1 5
2: 4 0 2
3: 4 0 1
4: 7 2 3
5: 2 2 3
6: 6 0 1
7: 3 0 2
8: 7 3 2
9: 4 0 1
10: 4 1 1
11: 6 3 1
12: 4 1 1
13: 4 0 1
14: 6 0 1
15: 5 1 2
16: 5 5 0
17: 9 0 3
18: 5 2 2
19: 5 1 2
20: 5 1 1

更新日期: 13-08-2021

5K+ 瀏覽

啟動您的事業

完成該課程認證

開始
廣告
© . All rights reserved.