Re: [R] Accessing elements of a list

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Wed, 25 May 2011 15:43:50 -0400

On May 25, 2011, at 3:25 PM, Seth W Bigelow wrote:

> I have a list that is made of lists of varying length. I wish to
> create a
> new vector that contains the last element of each list. So far I
> have used
> sapply to determine the length of each list, but I'm stymied at the
> part
> where I index the list to make a new vector containing only the last
> item
> of each list
>
> mylist = list(c(1,2,3),c("cat","dog"),c("x","y","z","zz")) #
> Create
> list
>
> last <- sapply(mylist,length) # Make vector with list lengths
>
> last_only <- mylist[[1:length(mylist)]][last] # Crash and burn
> trying to
> make new vector with last items!

If you wanted to apply the successive values of last using "[" to successive values of mylist there is a list-ish method via mapply:

 > mapply("[", mylist, last)
[1] "3" "dog" "zz"

`mapply` is also the function underlying `Vectorise`

-- 

David Winsemius, MD
West Hartford, CT

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Wed 25 May 2011 - 19:46:02 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 25 May 2011 - 20:20:09 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive