【发布时间】:2017-07-15 18:09:27
【问题描述】:
以下两个前两个函数查找向量x中的所有NA并将其替换为y
现在第一个函数:
f <- function(x, y) {
is_miss <- is.na(x)
x[is_miss] <- y
message(sum(is_miss), " missings replaced by the value ", y)
x
}
x<-c(1,2,NA,4,5)
# Call f() with the arguments x = x and y = 10
f(x=x,y=10)
#result is
1 missings replaced by the value 10
[1]1 2 10 4 5
第二个功能:
f <- function(x, y) {
is_miss <- is.na(x)
x[is_miss] <- y
cat(sum(is.na(x)), y, "\n")
x
}
x<-c(1,2,NA,4,5)
# Call f() with the arguments x = x and y = 10
f(x=x,y=10)
#result is
0 10
[1]1 2 10 4 5
这两个函数之间的唯一区别是每个函数中的 message/cat 行。为什么第一个函数打印 1 缺失值替换为值 10 但第二个打印 0 10 而不是 1 10 (它们都表示向量中的 1 NA 替换为值 10)。
【问题讨论】:
-
x向量在哪里? -
它们不等价:在第一个函数中使用
sum(is_miss),而在第二个函数中,在上一行更改x后使用sum(is.na(x))。 -
刚刚运行了这两个函数,它们都抛出了同样的错误。 @RichScriven 暗示:
Error in f(x = x, y = 10) : object 'x' not found。所以我将is.na更改为missing并且错误发生了变化,但功能仍然不起作用。错误变成了Error in x[is_miss] <- y : object 'x' not found。 -
@RichScriven 我的错。 x
-
@RuiBarradas 我将第二个函数更改为“sum(is_miss)”,结果是一样的。所以这一定是问题所在。但不是 'is_miss = is.na(x)' 吗?为什么它们会产生不同的结果?