简体   繁体   English

从表格显示中删除 NA

[英]Remove NA from Table Display

I have the following table that I generated using the table(data$a, data$b) function我有使用table(data$a, data$b)函数生成的下表

      a  b  c  NA
d  0  45 42 63 0
e  0  12 45 63 0
f  0  95 65 21 0
NA 0  0  0  0  0

How can I remove the columns with " " and NA?如何删除带有“”和 NA 的列?

Here is a reproducible example这是一个可重现的例子

a b
a d
a d
a d
a d
a d
a d
a d
a d
a d
a d
a d
a d
b d 
b d
b e
b e
b e
b e
c e
c e
c e
c e
c e
c e
c e
c e
c e
c e
c f
c f
c f
c f
c f
c f
c f
c f
c f
c f
c f

Note that there are no "" or NAs in the set, but they still appear in the table请注意,集合中没有 "" 或 NA,但它们仍然出现在表中

In this table, both of the variables are factors.在这个表中,两个变量都是因子。

Thank you!谢谢!

It is possible that the NA s are character strings "NA" instead of NA , otherwise, the table would pick up with default useNA= "no" and remove it. NA可能是字符串"NA"而不是NA ,否则,该table将使用默认的useNA= "no"并删除它。 One option is to change the values '' and "NA" to NA一种选择是将值''"NA"更改为NA

df1[df1 == "NA"|df1 == ""] <- NA

Assuming that we have two column dataframe and all of the columns are character class假设我们有两列数据框并且所有列都是character

Update更新

If the dataset have "NA" or "", it would be a factor class column with unused levels already existing.如果数据集有“NA”或“”,它将是一个factor类列,其中已存在未使用的级别。 One option is droplevels and then apply the table一种选择是droplevels然后应用table

table(droplevels(df1))

If we create a table called "mytable", you could try the following:如果我们创建一个名为“mytable”的表,您可以尝试以下操作:

bad_cols <- which(colnames(mytable) ==  "NA" || colnames(mytable) == "")
mytable <- mytable[, -bad_cols]

This will first find the positions in which we either have NA or "" in the column, then we exclude it via subsetting and save it in the variable „mytable“ again.这将首先找到列中我们有 NA 或 "" 的位置,然后我们通过子集排除它并再次将其保存在变量“mytable”中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM