У меня есть два пользовательских класса, которые имеют разные типы конструкторов и разные типы методов форматирования, один класс полагается на атрибуты объекта.
as.test_1 <- function(x, test_attribute, ...) {
attributes(x) <- list("test_attribute" = test_attribute)
x <-
structure(x, class = c("test_1", setdiff(class(x), "test_1")))
return(x)
}
format.test_1 <- function(x, ...) {
paste0(x, attributes(x)$test_attribute)
}
print.test_1 <- function(x, ...) {
cat(format(x, ...), "\n")
}
as.test_2 <- function(x, test_attribute, ...) {
x <-
structure(x, class = c("test_2", setdiff(class(x), "test_2")))
return(x)
}
format.test_2 <- function(x, ...) {
paste0(x, "test")
}
print.test_2 <- function(x, ...) {
cat(format(x, ...), "\n")
}
Теперь я хочу построить некоторые данные, которые содержат эти классы:
library(data.table)
data_1 <-
data.table(a = as.test_1(c(1, 2, 3, 4), test_attribute = "test"),
b = as.factor(c("a", "b", "c", "d")))
data_2 <-
data.table(a = as.test_2(c(1, 2, 3, 4), test_attribute = "test"),
b = as.factor(c("a", "b", "c", "d")))
Также я хочу использовать метод форматирования для форматирования оси Y. Это моя первая попытка, которая работает для класса test_2, который не использует атрибуты переменной для форматирования:
library(ggplot2)
plot_data <- function(data) {
g <- ggplot(data, aes(x = b, y = a))
g <- g + geom_bar(stat = "identity")
expand <- c(0, 0)
attributes(expand) <- attributes(data$a)
limits <- c(0, 4)
attributes(limits) <- attributes(data$a)
g <- g + scale_y_continuous(
expand = expand,
limits = limits,
oob = scales::squish,
labels = getS3method(f = "format", class = class(data$a)[[1]])
)
return(print(g))
}
Однако для класса test_1 кажется, что атрибуты теряются где-то при вызове scale_y_continuous.
plot_data(data_1)
![enter image description here](https://i.stack.imgur.com/kVXr6.png)
plot_data(data_2)
![enter image description here](https://i.stack.imgur.com/Rfi9e.png)
Кто-нибудь знает, как это исправить?
Спасибо!