1

我有两个构造 R S3 对象的函数。一个对象封装另一个。当用户将错误num参数传递给fun2()它时,会在fun2(). 我认为用户在fun1(). 有哪些选项可以保留 in 提出的消息fun1()并提出该消息而不是消息 in fun2()

fun1 <- function(num) {
  assert_that(num %% 2 == 0, msg = "num should be even")
  structure(num,
      class = "fun1-Class"
  )
}
fun2 <- function(text, num) {
  assert_that(class(num) == "fun1-Class", msg = "Bad Class")
  structure(list(text, num),
    class = "fun2-Class"
  )
}

fun1(1.2)
# Throws error "num should be even"

x <- fun2("myText", fun1(1.2))
# Throws error "Bad Class"

追溯如下

 Error: Bad Class 
3.
stop(assertError(attr(res, "msg"))) 
2.
assert_that(class(num) == "fun1-Class", msg = "Bad Class") 
1.
fun2("text", fun1(1.2)) 
4

1 回答 1

2

@aurèle在评论中回答了这个问题。

发生这种情况是因为对函数参数的惰性求值。force(num)将改变行为并评估第一个构造函数。

于 2020-04-06T14:33:40.937 回答