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

时间:2017-07-15 18:09:27

标签: r message cat

以下两个第一个函数查找向量x中的所有NAs,并将其替换为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替换。)

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

伊娃,你没有看到这个。在下面的代码中,我希望通过显示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