[R] Subsetting a list of vectors

Eric Lecoutre lecoutre at stat.ucl.ac.be
Mon Nov 10 09:02:49 CET 2003


I propose here a solution that relies on names of elements:

# From a list, with any names
# Make a copy to be able to change names


# Use unlist, which "autobuilds" names based on
# previous names and indexes in # vectors.
# Extracts 3 elements  when they exists



At 13:43 10/11/2003 +1300, Hadley Wickham wrote:
>I'm trying to subset a list which contains variable length vectors.
>What I want to do is extract (eg.) the 3rd item in each vector (with 
>length >= 3).  At the moment I'm using sapply(list.of.vectors, function(x) 
>{x[3]}).  The problem with this is that sapply returns a list of the same 
>length of list.of.vectors so I end up with a whole lot of null entries 
>from those vectors that aren't long enough.  I have a similar problem if I 
>want to select all the vectors where the 3rd item is a specified value.
>Does anyone have any better solutions?
>Thanks for you help,

L'erreur est certes humaine, mais un vrai désastre
nécessite un ou deux ordinateurs. Citation anonyme
Eric Lecoutre
Institut de Statistique / UCL

TEL (+32)(0)10473050       lecoutre at stat.ucl.ac.be
URL http://www.stat.ucl.ac.be/ISpersonnel/lecoutre

More information about the R-help mailing list