在 R 中创建参考 class 的初始化方法

Creating initialise method for reference class in R

我想为 R 中的引用 class 对象创建一个初始化方法,该方法将为缺少的参数提供默认值。在上面的示例中,引用 class 对象采用数据框和一些字符串。如果注释字符串缺失,则提供时间戳。

Class定义

#' Class SummaryData
#'
#' @description Odd class facilitating creation of data frame with
#'   summary information attached.
#'
#' @slot data data.frame.
#' @slot summary_columns character.
#' @slot info character.
#'
#' @return A SummaryData Class
#' @import methods
#' @exportClass SummaryData
#'
setClass(
    Class = "SummaryData",
    slots = list(
        data = "data.frame",
        summary_columns = "character",
        info = "character"
    )
)

#' Constructor method of SummaryData.
#'
#' @name SummaryData
#' @rdname SummaryData-class
setMethod("initialize", "SummaryData", function(.Object,
                                                data = "data.frame",
                                                summary_columns = "character",
                                                info = "character",
                                                ...)
{
    if (missing(data)) {
        data <- data.frame()
    }
    if (missing(summary_columns)) {
        summary_columns <- character()
    }
    if (missing(info)) {
        info <- paste("Object generated on:", Sys.time())
    }

    validObject(.Object)
    return(.Object)
})

#' Wrapper function SummaryData.
#'
#' @name SummaryData
#' @rdname SummaryData-class
#' @export
SummaryData <- function(...) {
    new("SummaryData", ...)
}

问题

>> SummaryData(data = airquality)
An object of class "SummaryData"
Slot "data":
data frame with 0 columns and 0 rows

Slot "summary_columns":
character(0)

Slot "info":
character(0)

想要的结果

您需要实际修改对象并调用您的 initialize 方法。

setClass(
  Class = "SummaryData",
  slots = list(
    data = "data.frame",
    summary_columns = "character",
    info = "character"
  )
)

# Constructor method of SummaryData.
setMethod("initialize", "SummaryData",
          function(.Object,
                   data,
                   summary_columns,
                   info,
                   ...) {

            if (!missing(data)) {
              .Object@data <- data
            }
            if (!missing(summary_columns)) {
              .Object@summary_columns <- summary_columns
            }
            if (missing(info)) {
              .Object@info <- paste("Object generated on:", Sys.time())
            }else {
              .Object@info <- info
            }

            validObject(.Object)
            return(.Object)
          }
)

# Wrapper function SummaryData.
SummaryData <- function(...) {
  initialize(new("SummaryData"), ...)
}

现在,一些测试:

SummaryData(data = airquality, info = "hey")
#Output not shown

SummaryData(data = data.frame(a = 1, b = 2))
#An object of class "SummaryData"
#Slot "data":
#  a b
#1 1 2
#
#Slot "summary_columns":
#character(0)
#
#Slot "info":
#[1] "Object generated on: 2018-12-12 20:21:09"