I would like to assert some expressions involving certain variable that is potentially evaluated to character(). I would like to print an assertation message showing the value of the variable which can be character().
assertthat::assert_that(<expr containing variable [x]>, msg = sprintf("Test for x failed on value %s" , x))
## Variable [x] is a character variable that can be character() or other conventional characters like `"a"`, `"b"` or ``"c"``.
Below is a simplified example to show the error I obtained when the variable is evaluated to character():
assertthat::assert_that(FALSE, msg = sprintf("%s", character()))
gives me error
## > Error in stop(assertError(attr(res, "msg"))) : bad error message
However the sprintf itself works well
sprintf("%s", character())
## character(0)
sprintf("%s", character()) %>% typeof
## [1] "character"
What I have tried:
- Wrap
%swith backticksassert_that(FALSE, msg = sprintf("`%s`", character())) - Load the
assertthatpackage first withlibrary(assertthat)then callassert_that(...) - Assign first
character()to a variable and call that variable inassert_thatwhich is actually more similar to my real life use casev <- character() assert_that(FALSE, msg = sprintf("`%s`", v)) - Assign the return value of
sprintfcall to a variable and then feed it into the call ofassert_thatv <- character() errmsg <- sprintf("`%s`", v) assert_that(FALSE, msg = errmsg)
All gave same error. It seems something inside assert_that affects.
What would be the reason of the error and how to fix it?
I think the problem here is that your
sprintfstatements results in a character with length0:This means there is not really a message for
assert_thatto print. So you have to ensure the length of thesprintfoutput has a length of 1: