简体   繁体   中英

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).

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") .

Eva, you are not seeing this right. In the code below I will, hopefully, make things clear by showing 3 different versions of your functions. I have named them f , g and h .

#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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM