[英]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.