[R] esoteric inconsistency -- intended or not?

Felix Andrews felix at nfrac.org
Sat Nov 8 02:06:34 CET 2008


2008/11/8 Bert Gunter <gunter.berton at gene.com>:
> Is the following intended or not?
>
>> func<- function(y) match.call()
>
>> z <- func(y =2)
>
>> z
> func(y = 2)
>
>> z[["a"]] <- 5
>
>> z
> func(y = 2, 5) ## Note that the second argument **is not** named
>
> ## BUT...
>
>> z <- func(y =2)
>
>> z$a <- 5
>
>> z
> func(y = 2, a = 5) ## The second argument **is** named
>
> ### End of example code ###
>
> The reason I ask is that the man page for [[ specifically says:
> **************
> Both [[ and $ select a single element of the list. The main difference is
> that $ does not allow computed indices, whereas [[ does. x$name is
> equivalent to x[["name", exact = FALSE]]. Also, the partial matching
> behavior of [[ can be controlled using the exact argument.
>
> [ and [[ are sometimes applied to other recursive objects such as calls and
> expressions. Pairlists are coerced to lists for extraction by [, but all
> three operators can be used for replacement.
>
> ********
>  I (mis?)read this as saying the behavior in the code snippets above should
> produce identical results.
>
> I note that the above inconsistency can be trivially avoided by first
> coercing the call object to a list, modifying it either way, and then
> coercing it back to a call object.

I too have been caught by this apparent inconsistency a few times.

By the way, another way to get around it is
z <- quote(func(y = 2))
z["a"] <- list(5)

Another inconsistency between the indexing of lists and calls is
recursive indexing, e.g.

## recursive indexing of lists works
> foo <- list(a = list(1, 2, 3), b = list(4, 5, 6))
> foo[[c(2,2)]]
[1] 5

## recursive indexing of calls fails
> foocall <- quote(func(a = list(1, 2, 3), b = list(4, 5, 6)))
> foocall[[c(3, 2)]]
Error in foocall[[c(3, 2)]] : attempt to select more than one element

OK, this is pretty obscure, and it is easy enough to write a function
to do it (as I have done), but it would be nice to have in the long
run, so that indexing is more standardised.


-- 
Felix Andrews / 安福立
http://www.neurofractal.org/felix/
3358 543D AAC6 22C2 D336  80D9 360B 72DD 3E4C F5D8



More information about the R-help mailing list