【发布时间】:2020-07-28 22:36:30
【问题描述】:
我有一个数据框列表
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 非常陌生,因此感谢任何帮助!
【问题讨论】: