why does initializing an R S4 class with a data.table slot not work if the variable is not provided

Viewed 507

I am trying to create an object containing a data.table and would like it to be initialized to an empty data.table if none is provided in the new statement. However I get an error message if I leave it out.

I tried using a data.frame instead which is fine but I would like to understand what goes wrong in the last new statment below since the first 2 new statments are good?

library(data.table)

setClass("TmpClass", slots = c(v1 = "character", v2 = "data.frame"))
new("TmpClass", v1 = "I work")
# An object of class "TmpClass"
# Slot "v1":
#   [1] "I work"
# 
# Slot "v2":
#   data frame with 0 columns and 0 rows

setClass("JunkClass", slots = c(v1 = "character", v2 = "data.table"))
new("JunkClass", v1 = "I work as well", v2 = data.table(a = 1, b = 2))
# An object of class "JunkClass"
# Slot "v1":
#   [1] "I work as well"
# 
# Slot "v2":
#    a b
# 1: 1 2

new("JunkClass", v1 = "hmm, i get an error")
# Error in validObject(.Object) : 
#   invalid class “JunkClass” object: invalid object for slot "v2" in class 
# "JunkClass": got class "list", should be or extend class "data.table"
1 Answers

I think a good solution here is to formally recognize the @v2 slot can be NULL.

library(data.table)
setClassUnion("nullOrDatatable", c("NULL", "data.table"))
setClass("JunkClass", slots = c(v1 = "character", v2 = "nullOrDatatable"))
new("JunkClass", v1 = "No more error!")
# An object of class "JunkClass"
# Slot "v1":
#   [1] "No more error!"
# 
# Slot "v2":
#   NULL
Related