[R] assignment functions with inherited class error

Martin Morgan mtmorgan at fhcrc.org
Thu Aug 12 06:31:38 CEST 2010


On 08/11/2010 04:42 AM, egc wrote:
> # Two test for a class like this:
> setClass("XXX",
> representation=representation(
> "matrix"
> )
> )
> 
> i<-new("XXX");
> m=matrix();
> colnames(m)<-c("colA");
> i at .Data=m;
> # >i
> # An object of class “XXX”
> #     colA
> #[1,]   NA
> #________________________________________________________________________
> #First Test 
> "varnames<-" <- function(x,value){
> colnames(x at .Data)<-value;
> }

Basically, you want to return x from your function, whereas here you are
returning 'value' (can you figure out why you are returning 'value'?)

Your S4 class deserves an S4 replacement method, so

  setClass("B", representation=representation("matrix"))
  setGeneric("varnames<-",
             function(x, ..., value) standardGeneric("varnames<-"))
  setReplaceMethod("varnames", "B", function(x, ..., value) {
      colnames(x at .Data) <- value
      x
  })

and

> b <- new("B", matrix())
> varnames(b) <- "ColA"
> b
An object of class "B"
     ColA
[1,]   NA

Martin

> #==========================================================
> #Result:
> # > varnames(i)<-c("a")
> # > i
> # [1] "a"
> # x lost class type an value from XXX to vector.  
> 
> #________________________________________________________________________
> # Second Test
> 
> "varnames<-" <- function(x,value){
> m=x at .Data;
> colnames(m)<-value;
> print(names(m)) #Ok the matrix is here. 
> slot(x,".Data")<-m;
> }
> #=========================================================
> #Result: 
> # x lost class type and value from XXX to matrix.
> # > varnames(i)<-c("colT") 
> # > i
> #     colT
> # [1,]   NA
> # > class(i)
> # [1] "matrix"
> 
> some idea?
> 
> Enrique Garzo Cano
> -Biology Graduate. Ph.D. student.-
> enrique.garzo.cano at gmail.com
> Departamento de Ciencias Biomédicas (Área de Fisiología) 
> Facultad de Veterinaria Universidad de León 
> 24071 León (Spain) 
> Tel: +34 987 291981 
> Fax: +34 987 291267
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Martin Morgan
Computational Biology / Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N.
PO Box 19024 Seattle, WA 98109

Location: Arnold Building M1 B861
Phone: (206) 667-2793



More information about the R-help mailing list