Re: [Rd] Why does not the command 'length(a <- 1:5) <- 4' not work?

From: Duncan Murdoch <murdoch_at_stats.uwo.ca>
Date: Tue 16 Jan 2007 - 19:12:39 GMT

On 1/16/2007 1:24 PM, Charles Dupont wrote:
> when running the command
> > length(a <- 1:5) <- 4
>
> there are two responses.
>
> If 'a' does not exist then the response is
>
> Error in length(a <- 1:5) <- 4 : object "a" not found
>
> If 'a' does exist then the response is
>
> Error in length(a <- 1:5) <- 4 : could not find function "<-<-"
>
> I would assume that 'length(a <- 1:5) <- 4' should work because
> 'length(a <- 1:5)' does work.

I'm guessing you are assuming it would mean the same as

a <- 1:5
length(a) <- 4

But how would R know the name of the variable whose length is set in the second line? In "a <- 1:5" the "a" is just part of a larger expression, it's not special as in some other languages, i.e. R sees that as

"<-"(a, 1:5)

So if you rewrote your original as

length("<-"(a, 1:5)) <- 4

it is a lot less clear that you really mean to create and then change "a".

In general things like

foo(a) <- b

are evaluated as "foo<-"(a, b), where "foo<-" is a function that expects a variable reference as its first argument. There's some magic going on to allow things like

a <- matrix(1:4, 2,2)
names(dim(a)) <- letters[1:2]

and I think the parser is trying to set things up for that kind of magic in your expression, though I haven't traced through the execution path to explain exactly why you saw the error messages you saw.

Duncan Murdoch



R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Wed Jan 17 06:16:10 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 16 Jan 2007 - 19:32:52 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.