具有容差的match()值

bap*_*ste 5 r subset floating-accuracy

我在绘图之前对数据集进行了子集化,但是关键是数字我不能使用严格的等式测试match()%in%(它错过了几个值).我写了以下替代方案,但我想这个问题很常见,有一个更好的内置替代方案?all.equal似乎不是为多个测试值设计的.

select_in <- function(x, ref, tol=1e-10){
  testone <- function(value) abs(x - value) < tol
  as.logical(rowSums(sapply(ref, testone)) )
}

x = c(1.0, 1+1e-13, 1.01, 2, 2+1e-9, 2-1e-11)
x %in% c(1,2,3)
#[1]  TRUE FALSE FALSE  TRUE FALSE FALSE
select_in(x, c(1, 2, 3))
#[1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)

Fra*_*ank 6

这似乎达到了目标(尽管不是很宽容):

fselect_in <- function(x, ref, d = 10){
  round(x, digits=d) %in% round(ref, digits=d)
}

fselect_in(x, c(1,2,3))
# TRUE  TRUE FALSE  TRUE FALSE  TRUE
Run Code Online (Sandbox Code Playgroud)