[英]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个缺失值,将其替换为值10,而第二个函数则打印0 10而不是1 10 (它们均表示矢量中的1 NA被值10替换)。
在第二个函数中, x[is_miss] <- y
替换NA。 当您在cat(sum(is.na(x)), y, "\\n")
重新检查它们的计数时,该计数将cat(sum(is.na(x)), y, "\\n")
语句之前的计数。 尝试用cat(sum(is.na(x)), y, "\\n")
替换第二个函数中的cat(sum(is_miss), y, "\\n")
。
伊娃,你没看到这个权利。 希望在下面的代码中,通过显示函数的3个不同版本来使事情变得清晰。 我将它们分别命名为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.