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