R中的此函数为什么在小数点前放置反斜杠?

问题描述 投票:1回答:1

我有以下功能,应该输出文本字符串,但是似乎在数字的小数点前加反斜杠:

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"

我该如何纠正该功能,以便它输出正确的(“均值= 3.25”)输出?

r
1个回答
4
投票

编辑:

废话,这行得通:

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,因为否则,否则[[any结果为数字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))
© www.soinside.com 2019 - 2024. All rights reserved.