[R] Index list by other list (w/ logical elements)?

Phil Spector spector at stat.berkeley.edu
Wed Aug 25 00:06:32 CEST 2010


Marianne  -
    The function you're looking for is mapply:

> mapply(function(one,two)one[two],x,y)
[[1]]
[1] "one"

[[2]]
[1] "four" "five"

 					- Phil Spector
 					 Statistical Computing Facility
 					 Department of Statistics
 					 UC Berkeley
 					 spector at stat.berkeley.edu




On Tue, 24 Aug 2010, Marianne Promberger wrote:

> I have two lists of the same shape, like this:
>
> x <- list()
> x[[1]] <- c("one","two")
> x[[2]] <- c("three","four","five")
>
> y <- list()
> y[[1]] <- c(TRUE,FALSE)
> y[[2]] <- c(FALSE,TRUE,TRUE)
>
> I would like to index x "by" y, that is, the result in this case
> should be:
>
> z
> [[1]]
> [1] "one"
>
> [[2]]
> [1] "four"  "five"
>
>
> I was hoping
> sapply(x,"[",y)
> would work, but it doesn't.
>
> I guess I need to sapply twice, like
> sapply(x, function() { sapply(y ...
> but I can't figure it out.
>
> Many thanks for any pointers
>
> Marianne
>
>
> -- 
> Marianne Promberger PhD, King's College London
> http://promberger.info
> R version 2.11.1 (2010-05-31)
> Ubuntu 9.04
>
> ______________________________________________
> 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