【问题标题】:How can I test for a data frame content?如何测试数据框内容?
【发布时间】:2020-01-21 10:17:38
【问题描述】:

我有一个返回数据框的例程。我想检查它的值是否合理。使用testthat 我有expect_equal,但我不确定它是否适用于data.frames。我试图这样做,但它不起作用

testthat::expect_equal(result$ORs[1,1:3], c(1.114308, 0.5406599, 2.296604), tolerance=1.0e-6)

这是我收到的消息

─────────────────────────────────────────────────
test-xxx.R:19: failure: basic functionality
result$ORs[1, 1:3] not equal to c(1.114308, 0.5406599, 2.296604).
Modes: list, numeric
names for target but not for current
Attributes: < Modes: list, NULL >
Attributes: < Lengths: 2, 0 >
Attributes: < names for target but not for current >
Attributes: < current is not list-like >
─────────────────────────────────────────────────

══ Results ══════════════════════════════════════
Duration: 0.1 s

【问题讨论】:

  • 您要测试整个数据框还是只测试特定行?还是将整行映射到多个值?
  • @NelsonGon 理想情况下,在这种情况下,我想检查每个值是否在给定的容差范围内。这对于小数据帧来说是微不足道的,但对于较大的数据帧,我将使用子集或沿列或行求和来检查最终值。
  • 不太确定,但您能解释一下它是如何失败的吗?使用“较低级别”compareall.equal 进行测试似乎有效。
  • @NelsonGon 编辑错误

标签: r testthat


【解决方案1】:

如果您只是测试特定列的值(例如df[1,1]),那么您可以unnameunlist 的值:

expect_equal(unname(unlist(df[1,1])), "Value")

【讨论】:

    【解决方案2】:

    问题是...$ORs[1, 1:3] 是另一个data.frame,因为您将一行包含多个列:

    # data example
    ORs <- data.frame(1:3, 0:2, 2:4)
    
    # show that it is a data.frame
    str(ORs[1, 1:3])
    #R> 'data.frame':   1 obs. of  3 variables:
    #R>  $ X1.3: int 1
    #R>  $ X0.2: int 0
    #R>  $ X2.4: int 2
    

    多行多于一列也会发生同样的情况。几个选项是:

    1. 将结果发送至dput 并使用输出(在可能将条目更改为预期值之后)。然后你确定你有正确的属性:
    dput(ORs[1, 1:3])
    #R> structure(list(X1.3 = 1L, X0.2 = 0L, X2.4 = 2L), row.names = 1L, class = "data.frame")
    
    expect_equal(
      ORs[1, 1:3], 
      structure(list(X1.3 = 1L, X0.2 = 0L, X2.4 = 2L), row.names = 1L, class = "data.frame"))
    
    # you can disregard the whole structure part if you use check.attributes = FALSE
    # That is just list(...) with the expected values
    expect_equal(ORs[1, 1:3], list(1L, 0L, 2L), check.attributes = FALSE)
    
    1. 使用expect_known_value 存储带有预期输出的.RDS 文件以进行测试。
    2. anpami 建议的那样,取消列出数据并进行测试。如果您正在查看的列中的所有 data.frame 条目都属于同一类型(这里是前三个),这将非常有效:
    expect_equal(unlist(ORs[1, 1:3]), c(1L, 0L, 2L), 
                 check.attributes = FALSE)
    
    1. 分别测试每个值。不过,这似乎不是一个不错的选择:​​i>
    expect_equal(ORs[1, 1], 1L)
    expect_equal(ORs[1, 2], 0L)
    expect_equal(ORs[1, 3], 2L)
    

    注意expect_equal 使用all.equal,所以让all.equal 通过是问题。

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多