Search code examples
rmessagecat

Two equivalent functions have two different outputs


The following two first functions find all NAs in a vector x and replace it with y

Now 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:

 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

The only difference between the two functions is the message/cat line in each function. Why the first function prints 1 missings replaced by the value 10 but the second prints 0 10 instead of 1 10 (they all mean 1 NA in the vector replaced by value 10).


Solution

  • In your second function x[is_miss] <- y replaces the NAs. When you recheck their count in cat(sum(is.na(x)), y, "\n"), it will be different than before the previous statement. Try replacing cat(sum(is.na(x)), y, "\n") in second function with cat(sum(is_miss), y, "\n").