[R] adding class attributes to strings: works in a loop, but not directly
Franckx Laurent
laurent.franckx at vito.be
Wed May 29 13:49:29 CEST 2013
Dear all
I try to assign class attributes to strings. Depending on the approach I use, it works (including method dispatch) or fails.
Let me clarify with an example.
Let:
> AONtptmodelist <- c("FOOT","BICY")
When I assign "class" attributes directly to these strings, it fails:
> class("BICY") <- "AONmode"
Error in class("BICY") <- "AONmode" :
target of assignment expands to non-language object
However, when I assign the attributes in a loop, it does work:
> for(tptmode in AONtptmodelist) {
+ class(tptmode) <- "AONmode"
+ cat("The value of is.object(tptmode) for " , tptmode , "is: " , is.object(tptmode) , ".\n")
+ cat("The class of " , tptmode , "is: " , class(tptmode) , ".\n")
+ }
The value of is.object(tptmode) for FOOT is: TRUE .
The class of FOOT is: AONmode .
The value of is.object(tptmode) for BICY is: TRUE .
The class of BICY is: AONmode .
Moreover, within this loop, method dispatch works correctly.
However, when I start a new loop over the same vector, I get:
> for(tptmode in AONtptmodelist) {
+ cat("The value of is.object(tptmode) for " , tptmode , "is: " , is.object(tptmode) , ".\n")
+ cat("The class of " , tptmode , "is: " , class(tptmode) , ".\n")
+ }
The value of is.object(tptmode) for FOOT is: FALSE .
The class of FOOT is: character .
The value of is.object(tptmode) for BICY is: FALSE .
The class of BICY is: character .
I find this troublesome for two reasons. First, I do not understand the difference between the two approaches. Why can I assign a class attribute to a string when it is called in a loop, but not directly? And why is the class attribution not permanent? Second, the problem was concealed until now precisely because I assigned the attributes in a link. However, I would like to centralise my class definition in one single place in my code, thus outside the loop where the methods are called.
Laurent Franckx, PhD
VITO NV
Boeretang 200, 2400 MOL, Belgium
Tel. + 32 14 33 58 22
Skype: laurent.franckx
laurent.franckx at vito.be
Visit our website: www.vito.be/english and http://www.vito.be/transport
[http://www.vito.be/e-maildisclaimer/vito.png]
Ontdek hoe VITO de transitie naar een duurzame maatschappij op gang trekt: www.vito.be/duurzaamheidsverslag2012<http://www.vito.be/duurzaamheidsverslag2012>
VITO Disclaimer: http://www.vito.be/e-maildisclaimer
More information about the R-help
mailing list