[R] navigating in lists

Erik Gregory egregory2007 at yahoo.com
Wed Jan 12 22:44:47 CET 2011


Or, if for some reason the lists differ in length...

test=list(a=list(1,2),b=list(3,4),c=list(5,6,7))


picker <- function(x, i) {
if(length(x)>=i)
  x[[i]]
else
  NA
}

pick <- function(list,i) {
sapply(list, function(x) picker(x, i))
}

> pick(test, 1)
a b c 
1 3 5 
> pick(test, 2)
a b c 
2 4 6 
> pick(test, 3)
 a  b  c 
NA NA  7 
> pick(test, 4)
 a  b  c 
NA NA NA 

-Erik Gregory
Student Assistant, California EPA
CSU Sacramento, Mathematics

----- Original Message ----
From: Greg Snow <Greg.Snow at imail.org>
To: Jannis <bt_jannis at yahoo.de>; "r-help at r-project.org" <r-help at r-project.org>
Sent: Wed, January 12, 2011 1:17:54 PM
Subject: Re: [R] navigating in lists

> sapply(test, '[[', 1)
a b c 
1 3 5

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Jannis
> Sent: Wednesday, January 12, 2011 1:50 PM
> To: r-help at r-project.org
> Subject: [R] navigating in lists
> 
> Dear list members,
> 
> 
> I am stuck with navigating in a rather complicated list object.
> 
> In general I would need a solution to access all first (or other)
> elements of the different sublists in one list:
> 
> test=list(a=list(1,2),b=list(3,4),c=list(5,6))
> 
> like:
> 
> test[[1:3]][[1]]
> 
> which should result in
> 
> c(1,3,5)
> 
> 
> Is there any way to access lists in such a way? Using unlist would
> create quite complicated objects....
> 
> Cheers
> Jannis
> 
> 
> 
> ______________________________________________
> 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.

______________________________________________
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.



More information about the R-help mailing list