如何为 R 中的列联表创建 NA 列?

要为 R 中的列联表创建 NA 列,我们可以按照以下步骤操作 -

  • 首先,创建一个具有两列的数据框,其中包含一些 NA 值。

  • 为两列创建列联表。

  • 使用 useNA 创建相同的表。

创建数据框

让我们创建一个数据框,如下所示 -

x<-sample(c(NA,1,2,3,4),25,replace=TRUE)
y<-sample(c(NA,10,12,13,15),25,replace=TRUE)
df<-data.frame(x,y)
df

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

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

创建列联表

使用 table 函数为 df 中的数据创建列联表 -

x<-sample(c(NA,1,2,3,4),25,replace=TRUE)
y<-sample(c(NA,10,12,13,15),25,replace=TRUE)
df<-data.frame(x,y)
table(df$x,df$y)

输出

 10 12 13 15
1 0 0   2 0
2 1 1   1 2
3 1 0   1 2
4 1 1   0 1

用 NA 创建列联表

使用 table 函数使用 useNA 参数为 df 中的数据创建列联表 -

x<-sample(c(NA,1,2,3,4),25,replace=TRUE)
y<-sample(c(NA,10,12,13,15),25,replace=TRUE)
df<-data.frame(x,y)
table(df$x,df$y,useNA="always")

输出

  10 12 13 15
1 0  0   2 0
2 1  1   1 2
3 1  0   1 2
4 1  1   0 1
1 1  0   1 2