#' @title Class conversion
#' @description Try converting an object into the desired class.
#' @param class `character`, specifying the desired output class.
#' @param x The object which is to be converted.
#' @param ... Further arguments passed to the class creator function.
#' @usage convert(x, class)
#' @return Depends on `class`
#' @examples
#' \donttest{
#' x <- rnorm(5)
#' convert(x, "data.frame")
#' }
#' @export
convert <- function(x, class, ...) {
y <- NULL
if (is.null(y)) {
y <- tryCatch(eval(parse(text = paste0("as.", class, "(x, ...)"))),
error = function(e) NULL)
}
if (is.null(y)) {
y <- tryCatch(eval(parse(text = paste0("as_", class, "(x, ...)"))),
error = function(e) NULL)
}
if (is.null(y)) {
stop("x cannot be coerced to class ", class)
}
return(y)
}
An example:
x <- rnorm(5)
x_syrup <- x
class(x_syrup) <- "syrup"
o <- convert(x, "data.frame")
o_syrup <- convert(x_syrup, "data.frame")
class(o) # data.frame
o
is converted to a data.frame
as expected, but o_syrup
is not since as.data.frame
does not know how to handle a syrup
class.
The error message for convert(x_syrup, "data.frame")
Error in convert(x_syrup, "data.frame") :
x cannot be coerced to class data.frame
What do you think about it? And how could it be improved?