Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 近似匹配(所有的模拟值相同)?_R_Precision - Fatal编程技术网

R 近似匹配(所有的模拟值相同)?

R 近似匹配(所有的模拟值相同)?,r,precision,R,Precision,考虑: (tmp1 <- seq(0, 0.2, 0.01)[16]) # [1] 0.15 (tmp2 <- seq(0, 0.2, 0.05)[4]) # [1] 0.15 其根本原因与此有关。但是,当尝试使用匹配识别序列中的子序列时,这会导致一个问题,例如: match(seq(0, 0.2, 0.05), seq(0, 0.2, 0.01)) # [1] 1 6 11 NA 21 匹配是否有一种替代方法,它类似于all.equal的相同?我们可以编写一个名为near.

考虑:

(tmp1 <- seq(0, 0.2, 0.01)[16])
# [1] 0.15
(tmp2 <- seq(0, 0.2, 0.05)[4])
# [1] 0.15
其根本原因与此有关。但是,当尝试使用
匹配
识别序列中的子序列时,这会导致一个问题,例如:

match(seq(0, 0.2, 0.05), seq(0, 0.2, 0.01))
# [1]  1  6 11 NA 21

匹配
是否有一种替代方法,它类似于
all.equal
相同

我们可以编写一个名为
near.match
的自定义
匹配,灵感来自
dplyr::near

near.match <- function(x, y, tol = .Machine$double.eps^0.5){
    sapply(x, function(i){
       res <- which(abs(y - i) < tol, arr.ind = TRUE)[1]
       if(length(res)) res else NA_integer_
    })
}

near.match(seq(0, 0.2, 0.05), seq(0, 0.2, 0.01))
# [1]  1  6 11 16 21
near.match(c(seq(0, 0.2, 0.05), 0.3), seq(0, 0.2, 0.01))
# [1]  1  6 11 16 21 NA

near.match可能与
round
匹配
match(round(tmp2,2),round(tmp1,2))
这是个好主意,所以我只需要巧妙地选择digits参数。@Alex-
round
对向量最有效。否则它将毫无用处。@TheLate Mail oops,误读了帮助文件中关于回合的部分:)虽然我喜欢这个答案的逻辑(使用
double.eps
),但我认为通过将逻辑构建到
回合
function@Alex,我认为给出一个
tol
更灵活,但缺点是效率较低。
near.match <- function(x, y, tol = .Machine$double.eps^0.5){
    sapply(x, function(i){
       res <- which(abs(y - i) < tol, arr.ind = TRUE)[1]
       if(length(res)) res else NA_integer_
    })
}

near.match(seq(0, 0.2, 0.05), seq(0, 0.2, 0.01))
# [1]  1  6 11 16 21
near.match(c(seq(0, 0.2, 0.05), 0.3), seq(0, 0.2, 0.01))
# [1]  1  6 11 16 21 NA