[英]Two equivalent functions have two different outputs
The following two first functions find all NAs in a vector x
and replace it with y
以下两个第一个函数在向量x
找到所有NA,并将其替换为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. 这两个功能之间的唯一区别是每个功能中的message / cat行。 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). 为什么第一个函数打印1个缺失值,将其替换为值10,而第二个函数则打印0 10而不是1 10 (它们均表示矢量中的1 NA被值10替换)。
In your second function x[is_miss] <- y
replaces the NAs. 在第二个函数中, x[is_miss] <- y
替换NA。 When you recheck their count in cat(sum(is.na(x)), y, "\\n")
, it will be different than before the previous statement. 当您在cat(sum(is.na(x)), y, "\\n")
重新检查它们的计数时,该计数将cat(sum(is.na(x)), y, "\\n")
语句之前的计数。 Try replacing cat(sum(is.na(x)), y, "\\n")
in second function with cat(sum(is_miss), y, "\\n")
. 尝试用cat(sum(is.na(x)), y, "\\n")
替换第二个函数中的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. 希望在下面的代码中,通过显示函数的3个不同版本来使事情变得清晰。 I have named them f
, g
and h
. 我将它们分别命名为f
, g
和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.