Konrad
Konrad

Reputation: 18657

Using missing within initialize method of a reference class

I'm looking to create a generator function for a dummy reference class that would create empty objects of correct classes if arguments are not given.

Code

#' 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(comment(info))) {
        info <- character()
    }

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

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

Problem

SummaryData(data = mtcars, summary_columns = c("cyl", "mpg"), info = "Cars data")

Gives this error:

Error in missing(comment(info)) : invalid use of 'missing'
SummaryData(data = mtcars, summary_columns = c("cyl", "mpg"))
Error in missing(comment(info)) : invalid use of 'missing'

Desired results

The second call should create SummaryData object with empty info string.

Upvotes: 0

Views: 122

Answers (1)

Taher A. Ghaleb
Taher A. Ghaleb

Reputation: 5240

Try using missing("data") or do.call(missing, list("data")) instead of missing(data). They both should work.

However, you cannot use it with comment(info), since missing only accepts argument names, but comment will rather return NULL. As long as the argument is supplied to a function call, it will not be missed, I guess. So, you'll need to check the argument info first and then do whatever you want.


Hope this helps.

Upvotes: 1

Related Questions