[R] Constructing lists (yet, again)
Marc Schwartz
marc_schwartz at me.com
Thu Jul 23 21:41:18 CEST 2009
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