[R] how to make list() return a list of *named* elements
Gabor Grothendieck
ggrothendieck at gmail.com
Thu Sep 30 15:10:16 CEST 2010
On Thu, Sep 30, 2010 at 7:49 AM, Hans Ekbrand
<hans.ekbrand at sociology.gu.se> wrote:
> If I combine elements into a list
>
> b <- c(22.4, 12.2, 10.9, 8.5, 9.2)
> my.c <- sample.int(round(2*mean(b)), 5)
> my.list <- list(b, my.c)
>
> the names of the elements seems to get lost in the process:
>
>> str(my.list)
> List of 2
> $ : num [1:5] 22.4 12.2 10.9 8.5 9.2
> $ : int [1:5] 11 8 6 9 20
>
> If I explicitly name the elements at list-creation, I get what I want:
>
> my.list <- list(b=b, my.c=my.c)
>
>> str(my.list)
> List of 2
> $ b : num [1:5] 22.4 12.2 10.9 8.5 9.2
> $ my.c: int [1:5] 11 8 6 9 20
>
>
> Now, is there a way to get list() (or some other function) to
> automatically name the elements?
>
> I often use list() in return(), and I am getting tired of having to
> repeat myself.
A data frame is a list in which every component (i.e. every column)
must have the same length (i.e. the same number of rows).
data.frame() does preserve names:
> data.frame(b, my.c)
b my.c
1 22.4 8
2 12.2 9
3 10.9 15
4 8.5 1
5 9.2 14
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list