【问题标题】:Match does not work匹配不起作用
【发布时间】:2013-04-24 22:55:33
【问题描述】:

我试图将数字与向量匹配,如下所示:

t <- seq(-4,4,length=81)

tifl.e <--1.5
tifc.e <--0.5
tifr.e <-0.5
tifl.m <--1.6
tifc.m <--0.4
tifr.m <-0.8

match( c(tifl.e, tifc.e, tifr.e), t)
[1] 26 36 46
match( c(tifl.m, tifc.m, tifr.m), t)
[1] NA NA NA

我也尝试了代码,但结果相同。

tifl.cut <-c(-1.5,-1.6)
tifc.cut <-c(-0.5,-0.4)
tifr.cut <-c(0.5,0.8)

match( c(tifl.cut[1], tifc.cut[1], tifr.cut[1]), t)
[1] 26 36 46
match( c(tifl.cut[2], tifc.cut[2], tifr.cut[2]), t)
[1] NA NA NA

同时,我使用 %in% 尝试了类似的语法,得到了完全相同的结果。

那么语法有什么问题呢?我应该如何解决它?

感谢您的意见。

【问题讨论】:

  • 浮点错误:t[25] == tifl.m 返回FALSE 所以match%in% will also. You could write your own version of match that does "fuzzy" matching using the all.equal` 函数代替!
  • 我认为,如果您要为问题命名“函数 XXX 不起作用”,最好真的确保它是功能问题而不是用户问题

标签: r match


【解决方案1】:

我认为你真的想要findInterval 而不是match

 findInterval( c(tifl.e, tifc.e, tifr.e), t)
#[1] 26 36 46
 tifl.m <--1.6
 tifc.m <--0.4
 tifr.m <-0.8
 findInterval( c(tifl.m, tifc.m, tifr.m), t)
#[1] 24 36 48

如果你想有公差系数,那么只需减去一个“模糊”:

findInterval( c(tifl.m, tifc.m, tifr.m)- 1e-10, t)
#[1] 24 36 48

【讨论】:

  • 根据浮点错误的符号,1 是对还是错。此外,即使第一个元素不是t 的成员,它也会始终返回结果,而match 将返回NA
  • 我通常在左侧添加一个-Inf,在右侧添加一个Inf,因此无需添加1。间隔在左侧关闭(我通常更喜欢)并且是不同于默认的cut 行为。
  • 我不是在谈论终点。想想findInterval(1.5, c(1, 2))match(1.5, c(1, 2)) 都给出了什么。
【解决方案2】:

处理浮点错误的正确方法是使用all.equal。这是一个自定义函数,用于将match 应用于数值并考虑浮点错误的可能性:

match.numeric <- function(x, table) {
   are.equal <- function(x, y) isTRUE(all.equal(x, y))
   match.one <- function(x, table)
      match(TRUE, vapply(table, are.equal, logical(1L), x = x))
   vapply(x, match.one, integer(1L), table)
}

match.numeric(c(tifl.e, tifc.e, tifr.e), t)
# [1] 26 36 46
match.numeric(c(tifl.m, tifc.m, tifr.m), t)
# [1] 25 37 49

【讨论】:

  • 演示isTRUE(all.equal(.))组合的积分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2017-11-04
  • 2013-07-20
  • 1970-01-01
  • 2012-07-15
  • 2017-05-07
  • 2017-04-25
相关资源
最近更新 更多