[R] Redefining [ using next method

Christophe Genolini cgenolin at u-paris10.fr
Fri Mar 20 21:46:39 CET 2009


Hi all,

I would like to use an object and to add some definition to the [ 
function, but I do not manage...
My objet is a "trajectories", a matrix whose columne name does contain 
information :

---------
trajectories <- function(traj,varName,time){
  colnames(traj) <- paste(varName,time,sep="")
  class(traj) <- c("trajectories","matrix")
  return(traj)
}
x <- trajectories(traj=matrix(1:12,4),varName="T",time=c(1,2,4))
--------------

Then I would like to define the [ operator in the following way :

---------------
 > x["varName"]
[1] "T"
 > x["time"]
[1] 1 2 4
 > x[1,]
1 5 9
 > x[,1]
1 2 3 4
----------------

For that, I write:

----------------
"[.trajectories" <- function(traj,slot,...){
    
if(slot=="varName"){return(gsub("(\\d+)$","",colnames(traj)[1],perl=T))}else{}
    
if(slot=="time"){return(as.numeric(gsub("(^.+\\D)(\\d+$)","\\2",colnames(traj),perl=T)))}else{}
    NextMethod()
}
----------------

The ["varName"],["time"] and [1,] work fine, but not [,1]
Any idea of what is wrong and how to correct?

Thanks
Christophe




More information about the R-help mailing list