【问题标题】:Why is this function in R placing a back slash in front of a decimal point?为什么 R 中的这个函数在小数点前放置一个反斜杠?
【发布时间】:2020-02-11 15:36:19
【问题描述】:

我有以下函数,它应该输出一串文本,但似乎在数字的小数点前添加了反斜杠:

myfunction <- function(x) {
    center <- mean(x)
    cat("Mean = ",center)
}

用一些数字测试一下:

library(testthat)

x <-c(1,2,3,7)

    expect_that(
        myfunction(x),
        prints_text("Mean = 3.25"))

Error: `x` does not match "Mean = 3.25".
Actual value: "Mean =  3\.25"

如何更正函数以打印正确的 ("Mean = 3.25") 输出?

【问题讨论】:

  • prints_text 需要一个正则表达式。请注意,. 是正则表达式中的特殊字符。
  • 请注意sep=" "cat 的默认值。

标签: r


【解决方案1】:

编辑:

废话,这行得通:

myfunction <- function(x) {
  center <- mean(x)
  cat("Mean =",center)
}

expect_that(
  myfunction(c(1,2,3,7)),
  prints_text("Mean = 3.25", fixed=TRUE))

即删除cat() 中的空格添加fixed = TRUE,否则任何结果的数字为3,后跟25的任何内容都将通过测试。

原始但可能是错误的答案:

这是因为testthat::prints_text 需要一个正则表达式。添加参数fixed = TRUE(并且\. 转义正则表达式中的文字点)

 prints_text("Mean = 3.25"),  fixed = TRUE)

最终编辑:

因为这似乎会引起混淆:

这个:

myfunction <- function(x) {
  center <- mean(x)
  cat("Mean =","3925")
}

通过测试(!):

library(testthat)
expect_that(
  myfunction(c(1,2,3,7)),
  prints_text("Mean = 3.25"))

但是没有通过这个测试:

library(testthat)    
expect_that(
  myfunction(c(1,2,3,7)),
  prints_text("Mean = 3.25", fixed=TRUE))

【讨论】:

  • 有什么方法可以在不调整 expect_that 代码的情况下解决问题?
  • 是的,我错了,但编辑了我的答案。我建议修复myfunction,因为现在它在等号后放置了两个空格。
  • 很抱歉给您带来了困惑!
  • 嗯,还是正则表达式的问题。如果函数是myfunction &lt;- function(...) cat("Mean = 3925"),它仍然可以通过测试。
  • 当然! MrFlick 是绝对正确的!我编辑了我的答案(再次;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2020-11-30
  • 2020-01-17
  • 2019-11-02
  • 2016-03-12
相关资源
最近更新 更多