r - R中用于继承自定义数据框类的列的函数
问题描述
我有一个数据框列表
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 非常陌生,因此不胜感激!
解决方案
我们可以imap
递归使用或map
在内部使用
library(purrr)
dd$dat <- imap(dd$dat, ~ {nm1 <- .y
map_dfr(append_classes(.x, nm1), ~ append_classes(.x, nm1))
})
class(dd$dat$one$a)
#[1] "numeric" "foo"
class(dd$dat$two$d)
#[1] "numeric" "bar"
或者这可以通过base R
使用来完成Map/lapply
dd$dat <- Map(function(x, y) {
tmp <- append_classes(x, y)
tmp[] <- lapply(tmp, append_classes, nm = y)
tmp} , dd$dat, names(dd$dat))
class(dd$dat$one$a)
#[1] "numeric" "foo"
推荐阅读
- php - 在 Lando 环境中编辑后自动加载的 php 代码未更新
- sql - 将空值设置为重复行,然后仅保留 1 行
- flask - 将我的本地烧瓶服务器配置为可用于同一 wifi 网络下的其他设备
- codeigniter - 付款表单操作在本地主机上工作,但在服务器上不起作用
- flutter - 多个浮动按钮 - Flutter
- javascript - 借助包装函数消除异步函数中的 try-catch 块
- mysql - 计算月平均值
- nuget - 尝试安装 ZXing.Net 库时,NuGet 包管理器控制台返回 InvalidOperation
- c# - EF Core 3.0 .Include 不能按预期工作并且超级慢
- python - LaunchAgent 脚本无法写入外部驱动器