如何在R中的data.table对象的每一列中找到零的数量?

要查找data.tableR 中对象的每一列中零的数量,我们可以按照以下步骤操作 -

  • 首先,创建一个data.table对象。

  • 然后,使用 colSums 函数查找每列中零的数量。

示例 1

创建data.table对象

让我们创建一个data.table如下所示的 -

library(data.table)
x1<-sample(0:2,25,replace=TRUE)
x2<-sample(0:2,25,replace=TRUE)
x3<-sample(0:2,25,replace=TRUE)
DT1<-data.table(x1,x2,x3)
DT1
输出结果

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

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

找出零的数量

使用 colSums 函数查找data.table对象 DT1 的每一列中的零数-

library(data.table)
x1<-sample(0:2,25,replace=TRUE)
x2<-sample(0:2,25,replace=TRUE)
x3<-sample(0:2,25,replace=TRUE)
DT1<-data.table(x1,x2,x3)
colSums(DT1==0)
输出结果
x1 x2 x3
 5  6 7

示例 2

创建data.table对象

让我们创建一个data.table如下所示的 -

library(data.table)
y1<-round(rnorm(25),0)
y2<-round(rnorm(25),0)
y3<-round(rnorm(25),0)
DT2<-data.table(y1,y2,y3)
DT2
输出结果

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

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

找出零的数量

使用 colSums 函数查找data.table对象 DT2 的每一列中的零数-

library(data.table)
y1<-round(rnorm(25),0)
y2<-round(rnorm(25),0)
y3<-round(rnorm(25),0)
DT2<-data.table(y1,y2,y3)
colSums(DT2==0)
输出结果
y1 y2 y3
 8 7 10