首页 > 解决方案 > 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"  

但现在我想使用类继承让每个数据框中的列分别继承foobarcustom类 - 我该怎么做?

期望的输出

class(dd$dat$one$a)
[1] "numeric" "foo"
class(dd$dat$two$d)
[1] "numeric" "bar"

我对使用 S3 非常陌生,因此不胜感激!

标签: rr-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"    

推荐阅读