【问题标题】:comparing two numerical variables in R比较 R 中的两个数值变量
【发布时间】:2016-01-15 21:39:56
【问题描述】:

我已经运行了 R 函数 stl() 函数并将其生成的残差用于 grubbs 测试。代码如下:

stl.res = stl(dataset, s.windows='periodic')
residuals = as.numeric(strl.res$time.series[, "remainder"])
grubbs.result = grubbs.test(residuals)

strsplit(grubbs.result$alternative," ")[[1]][3]
## [1] "38.4000349179783"

outlier = as.numeric(strsplit(grubbs.result$alternative," ")[[1]][3])
outlier
## [1] 38.40003492

which(residuals == outlier)
## integer(0)

我的问题是为什么which() 的返回值为0。实际上residuals[1920] = 38.4000349179783。所以which()的调用应该返回1921的值,而不是0。我猜这是精度的问题。我尝试了很多方法,但没有设法解决它。

【问题讨论】:

  • which(abs(residuals - outlier) < 1e-9) 这样的东西怎么样?

标签: r


【解决方案1】:

如果它真的是一个精度问题(这将是 R FAQ 7.31),那么有多种方法可以解决它。

# this is an approximation of your test
x <- c(1, 2, 38.4000349179783, 4, 5)
y <- 38.40003492

> x == y
[1] FALSE FALSE FALSE FALSE FALSE
# so which doesn't return anything


# one basic approach

> which(abs(x - y) < .00001)
[1] 3

你也可以使用 all.equal() 来装配一些东西,但是检查小于你预先选择的限制的差异可能是最简单的。

【讨论】:

    【解决方案2】:

    也许你可以使用isTrue()all.equal()如下:

    which(sapply(residuals, function(v) isTrue(all.equal(v,outlier))) == T)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多