[R] Which method is called in command like "class(x)='something'"?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Feb 15 18:58:36 CET 2010


On Mon, Feb 15, 2010 at 5:07 PM, blue sky <bluesky315 at gmail.com> wrote:
>> x=3
>> `class<-`(x,'something')#this command prints
> [1] 3
> attr(,"class")
> [1] "something"
>> x=3
>> class(x)='something'#this command doesn't print anything
>
> The first of the above two commands print the content of 'x' but the
> second doesn't, although both of them set the argument 'x'. I'm
> wondering which is method is called in the latter one.
>

The same thing is called. It's not a question of the method doing the
printing - the printing is done by the R interpreter when it finishes
evaluating your  line.

 Normally evaluations (eg sqrt(2)) print out but if you wrap them in
'invisible' they dont - try "invisible(sqrt(2))".

All assignments have their invisibility set when run interactively:

 > x=1:10
 > dim(x)=c(2,5)
 > x

 see how nothing is printed, either at the 'x=1:10' or the
'dim(x)=...'? Calling the assignment function directly returns a value
without the invisibility cloak, which is what you want when typing
'sqrt(2)':

> x=1:10
> `dim<-`(x,c(2,5))
    [,1] [,2] [,3] [,4] [,5]
[1,]    1    3    5    7    9
[2,]    2    4    6    8   10

 I suspect this behaviour is specified somewhere in the R parser. But
be honest, why does it matter? You would quickly get irritated by R
telling you what you just did every time you typed an assignment:

 > x=1:10
 [1] 1 2 3 4 5 6 7 8 9 10

Barry



-- 
blog: http://geospaced.blogspot.com/
web: http://www.maths.lancs.ac.uk/~rowlings
web: http://www.rowlingson.com/
twitter: http://twitter.com/geospacedman
pics: http://www.flickr.com/photos/spacedman



More information about the R-help mailing list