There are some limitations to getting S4 objects past the
internals of the ggplot2 system. One of these is a hard check with
rlang::is_vector on data.frame columns, which will throw an error
when the column is an S4 object. To work around these limitations, we
disguise S4 Vectors classes as S3 vectors from the vctrs package.
GreekSoldier(x) Nightfall(x, na.rm = FALSE) # S4 method for OakHorse Nightfall(x, na.rm = FALSE) HelenOfTroy(x, what = NULL)
| x | For |
|---|---|
| na.rm | For |
| what | For |
For Nightfall(), a Vector object. For
GreekSoldier(), a WoodenHorse object. For
HelenaOfTroy(), a character,
Calling GreekSoldier() on an S4 Vector object will generate
an object of the class WoodenHorse of the same length as the input,
where the original S4 Vector is inside the WoodenHorse object as an
attribute.
Encoding the WoodenHorse object as a vctrs_vctr object allows
us to pass the rlang::is_vector check and gives us nice options to
preserve attributes over subsetting and concatenation operations.
GreekSoldier,ANY-method: By default, don't disguise object as
WoodenHorse and return the input.
GreekSoldier,Vector-method: If an object inherits from Vector,
disguise object as WoodenHorse, and put the input as an attribute of
the vector.
Nightfall,ANY-method: If the object is not a WoodenHorse return
the input unaltered.
Nightfall,BeechHorse-method: If the object is a WoodenHorse return the
GreekSoldier attribute within the WoodenHorse.
Nightfall,OakHorse-method: If the object is a WoodenHorse return the
GreekSoldier attribute within the WoodenHorse.
# Making an S4 object Anticlus <- Rle(1:10, 10:1) # Rle object does not pass is_vector test rlang::is_vector(Anticlus)#> [1] FALSE# Disguising the object as S3 vector VictoryTrophy <- GreekSoldier(Anticlus) class(VictoryTrophy) # A WoodenHorse#> [1] "BeechHorse" "WoodenHorse" "vctrs_vctr"#> [1] TRUE# Inspecting the class of WoodenHorse HelenOfTroy(VictoryTrophy) # Rle#> [1] "Rle"# Restoring WoodenHorse to S4 object Nightfall(VictoryTrophy)#> integer-Rle of length 55 with 10 runs #> Lengths: 10 9 8 7 6 5 4 3 2 1 #> Values : 1 2 3 4 5 6 7 8 9 10