[R] R-devel not R-help (was "Bug? using { as a function ...")

Gabor Grothendieck ggrothendieck at myway.com
Wed Sep 29 17:33:17 CEST 2004


Martin Maechler <maechler <at> stat.math.ethz.ch> writes:

> 
> >>>>> "Gabor" == Gabor Grothendieck <ggrothendieck <at> myway.com>
> >>>>>     on Tue, 28 Sep 2004 20:02:01 +0000 (UTC) writes:
> 
>     Gabor> This seems like a bug to me.  Can someone verify
>     Gabor> this?
> 
> By the way, Gabor (and everyone else) :
> 
> This has been a typical topic *not* fitting well into R-help 
> (because it's quite technical and not about solving a real
>  problem with R, 

The real problem is how to create a list with given names
and constant content.  I find I need to do that and when I noticed
a recent problem posted on r-help that required it I decided it was 
time that I figured out a better way to do it.  I simplified the 
problem for purpose of bringing out the error more clearly but it
otherwise does stem from a real problem.

To illustrate, we will use this test data:

	nams <- letters[1:3]
	v <- 1:2

The following will do it:

	L <- rep(list(v), length(nams))
	names(L) <- nams

but I wanted a more compact expression.  This next line
reduces it from two statements to a single expression but I
still find it annoying that one must refer to nams twice
plus it seems there should be a shorter solution since it
seems like such a simple requirement:

	array(rep(list(v), length(nams)), dimnames = list(nams))

It occurred to me that this would be briefer:

	sapply(nams, function(x,y)v, simplify = F)

however, the anonymous function gives me a headache but 
further simplification does give

	sapply(nams, function(x,y)y, v, simplify = F)

and finally (except that this does not work) the following
is pleasingly compact:

	sapply(nams, "{", v, simplify = F) ###

which might seem a bit opaque but would be OK once you got used
to it as an idiom.  I ultimately settled on this:

	mapply("{", nams, list(v), SIMPLIFY = F)

which admittedly is only slightly longer than ### but its nevertheless
frustrating that ### gives an error.  

As an aside the next problem is how to create a general list with
given names such as 

	as.list(array(1:3, dimnames = list(nams)))
or
	array(as.list(1:3), dimnames = list(nams))

which works but its a bit annoying that one must first
create an array and then turn it into a list or visa
versa.  In this case the mapply solution generalizes:

	mapply("{", nams, 1:3, SIMPLIFY = F)

though, in practice, I would probably use the array
solution.  At any rate, I still would like to keep the
sapply solution, were it to work, around for the simpler
case and I think its important to get one's idioms straight.

More importantly, I think its nice to have
simple functions such as the identity function,
last argument function, etc. in one's arsenal as they
can often be combined with others in powerful ways so I
think it would be desirable to fix the { problem.




More information about the R-help mailing list