簡體   English   中英

創建從數據框繼承的 S4 class

[英]Create an S4 class inheriting from a data frame

我正在寫一個 R package。 在這個 package 中,我希望有一種特殊類型的數據幀,一些函數可以識別,具有一些額外的屬性,比如說,但在其他方面表現得與數據幀完全一樣。 實現我想要的一種方法就是在常規數據框上設置一些屬性:

   makedf <- function() {
     df <- data.frame(ID=1:3)
     attr(df, "myDF") <- TRUE
     attr(df, "source") <- "my nose"
     return(df)
   }

   dosmth <- function(df) {
     if(!is.null(attr(df, "myDF"))) message(sprintf("Oh my! My DF! From %s!", attr(df, "source")))
     message(sprintf("num of rows: %d", nrow(df)))
   }

dosmth()接收到“myDF”時,它具有有關數據幀來源的附加信息:

dosmth(data.frame(1:5))
#> num of rows: 5
dosmth(makedf())
#> Oh my! My DF! From my nose!
#> num of rows: 3

同樣,使用 S3 會相當簡單,我們甚至可以利用方法分派編寫不同的 dosmth 變體。 我如何用 S4 做到這一點?

我不完全確定這是否是您正在尋找的東西,但聽起來好像您希望能夠定義一個專門用於您的MyDFdata.frame的通用 function ,就像這個 reprex

MyDF <- setClass(Class = "MyDF",
                 slots = c(source = "character"),
                 contains = c("data.frame"))

setGeneric("dosmth", function(x) message("Can only dosmth to a df or MyDF"))

setMethod("dosmth", signature("data.frame"), 
          function(x) message(sprintf("num of rows: %d", nrow(x))))

setMethod("dosmth", signature("MyDF"), 
          function(x)  message(sprintf("Oh my! My DF! From %s!", x@source)))

a_df   <- data.frame(a = 1, b = 2)
a_MyDF <- MyDF(a_df, source = "my nose")

dosmth("my nose")
#> Can only dosmth to a df or MyDF
dosmth(a_df)
#> num of rows: 1
dosmth(a_MyDF)
#> Oh my! My DF! From my nose!

感謝@JDL 的評論指出我們不需要額外的“data.frame”插槽,以便可以正確繼承 data.frame 行為,如以下示例所示:

a_MyDF[1,]
#>   a b
#> 1 1 2

代表 package (v0.3.0) 於 2020 年 4 月 17 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM