I am reading an article on the {vctrs} package website (link to section), and at the bottom of the example of creating a percent class the following is stated:
Occasionally, it is useful to provide conversions that go beyond what’s allowed in casting. For example, we could offer a parsing method for character vectors. In this case, as_percent() should be generic, the default method should cast, and then additional methods should implement more flexible conversion:
as_percent <- function(x, ...) { UseMethod("as_percent") } as_percent.default <- function(x, ...) { vec_cast(x, new_percent()) } as_percent.character <- function(x) { value <- as.numeric(gsub(" *% *$", "", x)) / 100 new_percent(value) }
I am a little confused, because I understand from earlier on in the article that the difference between casting and coercing is whether it is done explicitly or implicitly respectively. This is why there are more casting methods than coercion methods, as some type conversions should only happen when the user knows what they are doing. I understand that the conversion from character
to percent
is a bit of a special case, but given this explicit vs implicit difference in casting and coercion I do not understand the first (bold) line in the quoted text above. Why aren't we defining vec_cast.percent.character()
? Since casting is explicit, shouldn't the result always be predictable to the user?