如何在 R 資料框的一列中找到不為零的值的數量?


如果一個 R 資料框包含數值列,那麼也可能存在一些或所有列中存在零,我們可能希望找到一列中非零值的個數。這將有助於我們根據非零值的個數比較列,並且可以透過使用 colSums 來實現。

示例

考慮以下資料框 -

 線上演示

x1<-sample(0:10,20,replace=TRUE)
x2<-sample(0:50,20,replace=TRUE)
x3<-sample(0:5,20,replace=TRUE)
x4<-sample(0:15,20,replace=TRUE)
x5<-sample(0:20,20,replace=TRUE)
df1<-data.frame(x1,x2,x3,x4,x5)
df1

輸出

  x1 x2 x3 x4 x5
1  9 47 4  1  6
2  7 6  1  7  7
3  3 20 5 15 19
4 10 13 2 13 13
5  10 49 1 8 12
6  10 49 1 2  1
7  9  36 5 2 15
8  0  27 4 15 8
9  6  50 2 7 15
10 7  11 0 10 4
11 9  22 1  7 14
12 5  47 5  3 20
13 3  36 2  0  6
14 10 44 4  6 18
15 1  40 2  11 4
16 1  46 0  15 5
17 3  36 5  0  9
18 2  1  5  6 19
19 9  38 3  4  1
20 1  37 4 11 18

查詢每列中不為零的值的數量 -

示例

colSums(df1!=0)

輸出

x1 x2 x3 x4 x5
19 20 18 18 20

讓我們看看另一個例子 -

示例

 線上演示

y1<-rpois(20,1)
y2<-rpois(20,2)
y3<-sample(0:1,20,replace=TRUE)
y4<-sample(0:2,20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2

輸出

   y1 y2 y3 y4
1  1  1   0 1
2  1  1   1 0
3  1  4   0 1
4  0  1   1 0
5  1  1   1 2
6  3  1   0 1
7  1  6   1 0
8  3  1   0 2
9  0  0   0 0
10 0  1   1 0
11 1  2   0 1
12 0  2   0 2
13 2  3   0 2
14 3  2   1 1
15 2  1   1 0
16 2  2   0 0
17 0  2   0 2
18 2  1   0 2
19 1  3   1 2
20 1  1   0 1

示例

colSums(df2!=0)

輸出

y1 y2 y3 y4
15 19 8 13

更新於: 2020-09-08

205 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.