[R] Whats wrong with NextMethod("[[<-")?
Henrik Bengtsson
hb at maths.lth.se
Sat Oct 25 17:23:42 CEST 2003
Hi. NextMethod("[[<-") do indeed call the "next" "[[<-"() method. The
thing is that it is also return the update object, which you are *not*
taking care of. You are just returning the same object again. So here is
what you want:
"[[<-.myA"<-function(mvl,name,value) {
if(data.class(value) == "myB") {
mvl$data[[name]] <- value
mvl
} else {
NextMethod("[[<-")
}
}
Also, it is better to use data.class(obj) than class(obj)[1].
Cheers
Henrik Bengtsson
Lund University
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Eryk Wolski
> Sent: den 25 oktober 2003 16:27
> To: r-help at stat.math.ethz.ch
> Subject: [R] Whats wrong with NextMethod("[[<-")?
>
>
> Hi!
>
> Given a list object "myA" with several fields
> i want to construct the assignment function "[[<-.myA"
> which behaves differently dependent of the class of the
> arguments (value).
>
> If value are a myB object it should append(assign) this
> massvector to the data field of myA object if its any other
> object the assignement function should work as for any list.
>
>
> "[[<-.myA"<-function(mvl,name,value)
> {
> if(class(value)[1]!="myB")
> {
> NextMethod("[[<-"); #work as a list
> }
> else
> {
> mvl$data[[name]] <- value #work as myA
> }
> mvl
> }
>
>
> test<-list(a=1,data=list(1))
> class(test)<-c("myA","list")
>
> duda<-"hello"
> class(duda)<-"myB"
>
> test[[2]]<-duda #works
> test[["newField"]]<-"bella" #nothing happens!!!
>
> The assignment test[["newField"]]<-"bella" has no effect. The
> list test are not extended by the entry newField. Looks to me
> like NextMethod("[[<-") does nothing.
>
> Is it possible to do this what I try to do with S3?
> If so what i do wrong?
> If its not possible to do this in this way can anyone suggest
> a different solution to what i like to do?
>
> Eryk
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailma> n/listinfo/r-help
>
>
More information about the R-help
mailing list