Skip to contents

Checks whether a vector can be coerced to character without losing information, returning it silently if so. Otherwise an informative error message is signaled. to_character is a synonym of to_chr().

Usage

to_chr(
  x,
  ...,
  x_arg = caller_arg(x),
  call = caller_env(),
  x_class = object_type(x)
)

to_character(
  x,
  ...,
  x_arg = caller_arg(x),
  call = caller_env(),
  x_class = object_type(x)
)

Arguments

x

The object to stabilize.

...

Arguments passed to methods.

x_arg

(character(1)) The name of the object being stabilized to use in error messages. The automatic value will work in most cases, or pass it through from higher-level functions to make error messages clearer in unexported functions.

call

(environment) The execution environment to mention as the source of error messages.

x_class

(character(1)) The class name of the object being stabilized to use in error messages. Use this if you remove a special class from the object before checking its coercion, but want the error message to match the original class.

Value

The input as a character vector.

Details

This function has two important differences from base::as.character():

  • lists and data.frames are not coerced to character. In base R, such objects are coerced to character representations of their elements. For example, as.character(list(1:3)) returns "1:3". In the unlikely event that this is the expected behavior, use as.character() instead.

  • NULL values can be rejected as part of the call to this function (with allow_null = FALSE).

Named functions are converted to their string name. If the function comes from a package namespace, the result is a "pkg::fn" string. For example, to_chr(mean) returns "base::mean". Anonymous functions produce an error.

To preserve the original call-site symbol when to_chr() is called inside a wrapper function, use the embrace operator {{ }}. For example:

my_wrapper <- function(fn) {
  to_chr({{ fn }})
}
my_wrapper(mean)  # Returns "base::mean"

Examples

to_chr("a")
#> [1] "a"
to_chr(letters)
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
#> [20] "t" "u" "v" "w" "x" "y" "z"
to_chr(1:10)
#>  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"
to_chr(1 + 0i)
#> [1] "1+0i"
to_chr(NULL)
#> NULL
try(to_chr(NULL, allow_null = FALSE))
#> Error in eval(expr, envir) : `NULL` must not be <NULL>.

# Named functions are converted to their string name.
to_chr(mean)
#> [1] "base::mean"
to_chr(base::mean)
#> [1] "base::mean"
try(to_chr(function(x) x))
#> Error in eval(expr, envir) : 
#>   Can't coerce `function(x) x` <function> to <character>.
#>  Anonymous functions can't be converted to a string name.