I guess there are several ways to do this. Hence, the answers to this question could be subjective, if not opiniated. So I will try to narrow the problem, and give you the details of what I have already done.
Context
I am working with the R6 package and I have created an IntervalNumeric
R6Class which has two fields lower_bound and upper_bound:
require(R6)
NumericInterval <-
R6Class(
"NumericInterval",
public = list(
lower_bound = NA,
upper_bound = NA,
initialize = function(low, up) {
self$lower_bound <- low
self$upper_bound <- up
},
as_character = function() {
paste0("[", self$lower_bound, ", ",
self$upper_bound, "]")}))
I have also use the S3 generic method system to get an as.character and printfor the
NumericInterval type:
as.character.NumericInterval <- function(x, ...) {
x$as_character()}
print.NumericInterval <- function(x, ...) {
x$as_character()}
Now I can do this (and the same with print):
> as.character(NumericInterval$new(0, pi))
[1] "[0, 3.14159265358979]"
Question:
What is needed to do now to use this new type as a data.frame column type?
For example I want to be able to do this:
(df <- data.frame(
X = c("I1", "I2", "I3"),
Y = c(NumericInterval$new(0,1),
NumericInterval$new(1,2),
NumericInterval$new(2,3)))
and get :
X Y
1 I1 [0, 1]
2 I2 [1, 2]
3 I3 [2, 3]
but I get :
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class ‘c("NumericInterval", "R6")’ to a data.frame
Of course I want also to be able to access objects and do things like:
df[2, 2]$lower_bound <- 0
tibbles seem to be a solution
(df <- tibble(
X = c("I1", "I2", "I3"),
Y = c(NumericInterval$new(0,1),
NumericInterval$new(1,2),
NumericInterval$new(2,3))))
produces:
# A tibble: 3 x 2
X Y
<chr> <list>
1 I1 <NmrcIntr>
2 I2 <NmrcIntr>
3 I3 <NmrcIntr>
And each NumericInterval is placed as expected eg:
> require(dplyr)
> df[2,1][[1]] %>% pull
[[1]]
<NumericInterval>
Public:
as_character: function ()
clone: function (deep = FALSE)
initialize: function (low, up)
lower_bound: 0
upper_bound: 1
But the output of the tibble and the way to access to the object is not what I expect.