This looks like an xy problem, but the following function should work in many cases:
convertClass <- function(from, to){ stopifnot(is.atomic(c(unclass(to)))) if (is.factor(to)) return(factor(from)) if (inherits(to, "POSIXct")) return(as.POSIXct(from)) tryCatch(as(from, class(to)), error = function(e) {class(from) <- class(to); from})}
It fails in your first test case but so does as.logical
.