Question

I want to create a new class in R which basically should be like the vector class except that every element in the vector has two additional attributes for 'start-time' and 'end-time'. Part of the functionality should be every sort of conventional indexing.

Providing at least a bit of code here is what I tried:

  setClass(
      Class = "Intervals",
      representation = representation(
        start.time = "POSIXct",
        end-time = "POSIXct",
        numbers = "numeric"),
      contains = "vector"
    )

This obviously doesn't work since after

iv <- function(start.time, end.time, numbers) {
  new(Class="Intervals", start.time = start.time, 
      end.time = end.time, numbers = numbers)
}

and

st <- seq(1,5)*3600+as.POSIXct("1970-01-01 01:00")
et <- seq(2,6)*3600+as.POSIXct("1970-01-01 01:00")
numbers <- c(1,2,3,4,5)
example <- iv(st,et,numbers)

example[1:3] e.g. gives me NA NA NA.

Or have I to write the getter by myself beginning with something like

setMethod(
  f = "[",
  signature="Intervals",
  definition=function(x,i,j,drop){
...

? Of course I wanted to avoid this since i don't know how to handle the arguments x,i,j,drop correctly.

Do I need the slot 'numbers'? Is there a way of inheriting from virtual class vector that allows me omitting it? Additionally I dont want to constrain the structure on vectors containing numeric values.

I hope this question is not too trivial but i read different chapters in books and pdfs whitout finding a solution by myself.

Thanks a lot in advance.

Mika

Was it helpful?

Solution

Ok. Meanwhile i managed (with the help of How to define the subset operators for a S4 class?) to come up with (after some renaming):

setMethod(
  f = "[",
  signature="Intervals",
  definition=function(x,i,j,...,drop=TRUE){ 
    initialize(x, from=x@from[i], to=x@to[i], values = x@values[i])
  }
)

Just if anyone is interested.. the show method looks like this.

setMethod(
  f = "show",
  signature="Intervals",
  definition=function(object){
    rownames <- sapply(seq_along(object@to), 
                       function (i) paste(object@from[i], "--", object@to[i]))
    df.show <- data.frame(object@values, row.names = rownames)
    names(df.show) <- ifelse(length(names(object@values)) == 0,
                             "Values", names(object@values))
    print (df.show)
  }
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top