I would like to ask for an advice regarding xts subclass. I am using xtsAttributes to add metadata information for every column of my xts numeric matrix. The metadata holds a character string with a description for each column.
So ncol(myxtsobject) = length(metadata). And I add a new class to the object as well, say myclass. Now I want to write method [.myclass extending [.xts function to also subset accordingly my metadata when subsetting xts matrix.
For example: d <- myobject[,c(2,3,23)] would produce d with 3 columns and appropriate 3 entries in metadata attributes.
Could somebody give me directions how to do it while rationally employing existing xts and matrix subsetting functions?
More details ….
There is the structure of my object below (just an minimalistic example):
# creating the object
n <- 10
ind <- Sys.time() + 1:n
col <- sin(seq(from=0, to=2*pi, length.out=n))
col2 <- cos(seq(from=0, to=2*pi, length.out=n))
d <- xts(x=cbind(col,col2), order.by=ind)
KEY1 <- paste("desc k1 -",1:ncol(d))
KEY2 <- paste("desc k2 -",1:ncol(d))
xtsAttributes(d) <- data.frame(KEY1,KEY2,stringsAsFactors=F)
d <- structure(d, class = c("dm", "xts", "zoo"))
# resulting structure
str(d)
Now, with such an object I would like to develop set of functions allowing subsetting consitent with object metadata KEY1, KEY2 so if I drop/select column 2, I will drop/select corresponding member from KEY1 and KEY2.
I am currently usig this code, which so far works. Reusing data.frame and xts subset.
These getMeta.dm(x) and is.dm(x) are my functions with obvious function.
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#: subset.dm
#:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
subset.dm <- function(x,i,j,...) {
# get my metadata, returns data.frame
md <- getMeta.dm(x)
# metadata subset
md <- md[j,]
# xts subset
myclass <- class(x)
x <- as.xts(x)
x <- x[i,j,...]
# now again assembling md object
# TODO fu() for creating dm objects
xtsAttributes(x) <- md
class(x) <- myclass
if(is.dm(x)) return(x) else stop("result is not dm object")
}
`[.dm` <- subset.dm
You need to create a subsetting function for your subclass that handles the columnar metadata attributes:
Now that we’ve defined the subclass subsetting function, let’s test it:
Looks good. Note that you can continue to use the xts-style subsetting functionality: