【问题标题】:Function for columns to inherit custom class of data frame in RR中用于继承自定义数据框类的列的函数
【发布时间】: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"  

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

期望的输出

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

我对使用 S3 非常陌生,因此感谢任何帮助!

【问题讨论】:

    标签: r r-s3


    【解决方案1】:

    我们可以递归使用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"    
    

    【讨论】:

    • 谢谢,但我收到警告 In bind_rows_(x, .id) : Vectorizing 'numeric' elements may not preserve their attributes 并运行 class(dd$dat$two$d) 只会导致数字 - 我错过了什么吗?
    • @MayaGans 你能检查我的更新吗?之前,我在理解属性方面犯了一个错误。
    • 谢谢!基本 R 版本可以工作,但purrr 版本会抛出警告In bind_rows_(x, .id) : Vectorizing 'numeric' elements may not preserve their attributes,有趣的是,当向量是字符时它可以工作,但如果是数字,它不会添加foo 类你知道为什么会这样吗?跨度>
    • @MayaGans 与 tidyverse,每个版本都可能有很多变化,这可能是一个问题。 purrrdplyr 的软件包版本是什么
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2020-10-28
    • 2021-11-20
    • 2018-03-03
    • 2016-04-13
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多