[R] Constructing lists (yet, again)

roger koenker rkoenker at uiuc.edu
Thu Jul 23 16:52:39 CEST 2009


Marc,

Thanks,

	sapply(ls(pat = "^name"),get)

was exactly what I was after.  The default behavior for vectors of
equal length is nice too, but I was most interested in the ragged
case, which produces a list.


url:    www.econ.uiuc.edu/~roger            Roger Koenker
email    rkoenker at uiuc.edu            Department of Economics
vox:     217-333-4558                University of Illinois
fax:       217-244-6678                Urbana, IL 61801



On Jul 23, 2009, at 2:41 PM, Marc Schwartz wrote:

> On Jul 23, 2009, at 9:19 AM, roger koenker wrote:
>
>> This is an attempt to rescue an old R-help question that apparently  
>> received
>> no response from the oblivion of collective silence, and besides  
>> I'm also
>> curious about the answer
>>
>>> From: Griffith Feeney (gfeeney at hawaii.edu)
>>> Date: Fri 28 Jan 2000 - 07:48:45 EST   wrote (to R-help)
>>> Constructing lists with
>>>
>>> list(name1=name1, name2=name2, ...)
>>>
>>> is tedious when there are many objects and names are long. Is  
>>> there an R
>>> function that takes a character vector of object names as an  
>>> argument and
>>> returns a list with each objected tagged by its name?
>>>
>> The idiom
>>
>> 	lapply(ls(pat = "^name"), function(x) eval(as.name(x)))
>>
>> makes the list, but (ironically)  doesn't assign the names to the  
>> components.
>
> Roger,
>
> How about something like this:
>
> name1 <- 1:3
> name2 <- 1:5
> name3 <- 1:9
> name4 <- 1:7
>
>
> > ls(pat = "^name")
> [1] "name1" "name2" "name3" "name4"
>
>
> > sapply(ls(pat = "^name"), get, simplify = FALSE)
> $name1
> [1] 1 2 3
>
> $name2
> [1] 1 2 3 4 5
>
> $name3
> [1] 1 2 3 4 5 6 7 8 9
>
> $name4
> [1] 1 2 3 4 5 6 7
>
>
> Is that what you are after? With sapply(), you can take advantage of  
> the USE.NAMES argument, which defaults to TRUE and then set simplify  
> to FALSE to force the result to be a list rather than a matrix. Of  
> course, in the case I have above, when there are uneven length  
> elements, the result will be a list anyway.
>
> HTH,
>
> Marc Schwartz




More information about the R-help mailing list