我有一个数据框列表
dd <- list()
dd$dat <- list(
one = data.frame(a = c(1), b = c(2)),
two = data.frame(c = c(3), d = c(4)),
three = data.frame(e = c(5), f = c(6))
)
并编写了一个函数来为每个数据框附加一个自定义类:
# append classes
append_classes <- function(x, nm) {
class(x) <-
case_when(
nm == "one" ~ c(class(x), "foo"),
nm == "two" ~ c(class(x), "bar"),
TRUE ~ c(class(x), "custom")
)
return(x)
}
dd$dat <- imap(dd$dat, append_classes)
class(dd$dat[[1]])
有用!
[1] "data.frame" "foo"
但现在我想使用类继承让每个数据框中的列分别继承foo
、bar
和custom
类 - 我该怎么做?
期望的输出
class(dd$dat$one$a)
[1] "numeric" "foo"
class(dd$dat$two$d)
[1] "numeric" "bar"
我对使用 S3 非常陌生,因此不胜感激!