两个等价函数有两个不同的输出

Two equivalent functions have two different outputs

下面的前两个函数在向量 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 missings 替换为值 10 但第二个函数打印 0 10 而不是1 10(它们都表示向量中的 1 个 NA 被值 10 替换)。

在您的第二个函数中,x[is_miss] <- y 替换了 NA。当您在 cat(sum(is.na(x)), y, "\n") 中重新检查它们的计数时,它将与之前的语句之前不同。尝试用 cat(sum(is_miss), y, "\n").

替换第二个函数中的 cat(sum(is.na(x)), y, "\n")

伊娃,你没看对。在下面的代码中,我希望通过显示函数的 3 个不同版本来使事情变得清晰。我将它们命名为 fgh.

#The first function
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

#The second function:
g <- 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 g() with the arguments x = x and y = 10
g(x=x,y=10)
0 10 
[1]  1  2 10  4  5

#The third function:
h <- function(x, y) {
    is_miss <- is.na(x)
    x[is_miss] <- y
    cat(sum(is_miss), y, "\n")  # ONLY DIFFERENCE FROM 'g'
    x
}
x<-c(1,2,NA,4,5)
# Call h() with the arguments x = x and y = 10
h(x=x,y=10)
1 10 
[1]  1  2 10  4  5