如何在 R 的 data.table 物件中查詢具有相同名稱的列的行中位數?


要查詢 R 中 data.table 物件中具有相同名稱的列的行中位數,我們可以按照以下步驟操作:

  • 首先,建立一個包含一些具有相同名稱的列的 data.table。

  • 然後,使用 tapply 以及 colnames 和 median 函式來查詢具有相同名稱的列的行中位數。

示例

建立 data.table

讓我們建立一個如下所示的 data.table:

library(data.table)
DT<-
data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),x=rpois(25,4),y=rpo is(25,10),check.names=FALSE)
DT

輸出

執行上述指令碼後,將生成以下輸出(由於隨機化,此輸出將在您的系統上有所不同):

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

查詢具有相同名稱的列的行中位數

使用 tapply 以及 colnames 和 median 函式來查詢 data.table 物件 DT 中具有相同名稱的列的行中位數:

library(data.table)
DT<-
data.table(x=rpois(25,5),y=rpois(25,10),x=rpois(25,5),y=rpois(25,2),x=rpois(25,4),y=rpo is(25,10),check.names=FALSE)
t(apply(DT,1, function(x) tapply(x,colnames(DT),median)))

輸出

      x y
[1,]  6 9
[2,]  4 9
[3,]  2 6
[4,]  6 9
[5,]  2 9
[6,]  6 4
[7,]  3 8
[8,]  5 10
[9,]  7 5
[10,] 7 10
[11,] 3 5
[12,] 6 10
[13,] 4 5
[14,] 4 9
[15,] 6 10
[16,] 6 7
[17,] 4 8
[18,] 7 9
[19,] 4 7
[20,] 4 12
[21,] 5 9
[22,] 3 9
[23,] 4 12
[24,] 4 6
[25,] 2 5

更新時間: 2021年11月10日

87 次檢視

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告