将所有零替换为 NA:
df[df == 0] <- NA
解释
1.它不是NULL
你应该用什么来替换零。正如它所说?'NULL'
,
NULL代表R中的空对象
which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that
data.frame(x = c(1, NULL, 2))
# x
# 1 1
# 2 2
That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA'
we see that
NA 是长度为 1 的逻辑常量,其中包含缺失值
指标。 NA 可以强制为除原始向量之外的任何其他向量类型。
重要的,NA
长度为1,因此R为其保留了一些空间。例如。,
data.frame(x = c(1, NA, 2))
# x
# 1 1
# 2 NA
# 3 2
此外,数据帧结构要求所有列具有相同数量的元素,以便不存在“漏洞”(即,NULL
值)。
现在您可以将零替换为NULL
在数据帧中,完全删除包含至少一个零的所有行。使用时,例如var
, cov
, or cor
,这实际上相当于首先用NA
并设置值use
as "complete.obs"
。然而,通常这并不令人满意,因为它会导致额外的信息丢失。
2.在我使用的解决方案中,不是运行某种循环df == 0
矢量化。df == 0
返回(尝试一下)与以下大小相同的矩阵df
,与条目TRUE
and FALSE
。此外,我们还可以将该矩阵传递给子集[...]
(see ?'['
)。最后,虽然结果df[df == 0]
是完全直观的,这可能看起来很奇怪df[df == 0] <- NA
给出了所需的效果。赋值运算符<-
确实并不总是那么聪明,并且不能以这种方式处理其他一些对象,但它可以处理数据框;看?'<-'
.
1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.