[R] Question about creating lists with functions as elements
Craig P. Pyrame
crappyr at gmail.com
Tue Jun 30 14:34:38 CEST 2009
Dear Barry,
Thank you for the suggestion, it does work. I think the documentation
might be improved, but it's probably not a good idea to submit bug
reports just because I misunderstand what R does.
Best regards,
Craig
Barry Rowlingson wrote:
> On Tue, Jun 30, 2009 at 1:00 PM, Craig P. Pyrame<crappyr at gmail.com> wrote:
>
>
>> But this fails, as above. Why? Why can c(character, character) create a
>> list of two functions, but rep(character, 2) can't?
>>
>> Another solution to my problem I could find (and you'll hopefully suggest an
>> even better one) is to use class names instead, like so:
>>
>>
>>> types = lapply(c(rep('character', 2), 'integer', 'numeric', ...),
>>> function(type) vector(type, 0))
>>>
>> but I am still curious why the above doesn't work as I would expect it to.
>>
>>
>
> I hope this doesn't turn into a debate about expectations vs what
> actually happens :)
>
> I've discovered that rep(list(f),n) might do what you want:
>
> > f=function(x){x*2}
> > l=rep(list(f),5)
> > l[[1]](4)
> [1] 8
>
> help(rep) says "It is a generic function" which translates to "you
> may have some problem finding out exactly what function is called when
> you do rep(thing)". I don't think there's a method for functions, so
> it's probably being passed to the generic method which is expecting
> vectors. It possibly then tries to get an element of f, and fails, a
> bit like this:
>
> > f[1]
> Error in f[1] : object of type 'closure' is not subsettable
>
> - without first checking if the object is a vector (you can do
> rep(c(1,2),5) you see). Maybe a bug, or a misleading error message, or
> a documentation problem: check with the latest version of R etc etc
> etc read the FAQ before submitting a bug etc etc etc.
>
> Barry
>
More information about the R-help
mailing list