[R] Indexing a list with a list
Greg Hirson
ghirson at ucdavis.edu
Fri Jun 26 20:37:19 CEST 2009
Jim,
Thank you for your help. I had a feeling it would be an apply function
that could help.
Kind regards,
Greg
jim holtman wrote:
> Your example has one more element in 'ind' than 'example' and that is
> what causes the error, but this should be close.
>
> > #sample data
> > set.seed(100)
> > example = list(letters[1:10], letters[1:10], letters[1:10])
> > ind = list(as.logical(sample(0:1, 10, rep=TRUE)),
> + as.logical(sample(0:1, 10, rep=TRUE)),
> + as.logical(sample(0:1, 10, rep=TRUE)),
> + as.logical(sample(0:1, 10, rep=TRUE)))
> >
> > mapply(function(a,b)a[b], example, ind)
> [[1]]
> [1] "c" "g" "i"
>
> [[2]]
> [1] "a" "b" "e" "f" "j"
>
> [[3]]
> [1] "a" "b" "c" "d" "g" "h" "i"
>
> [[4]]
> [1] "b" "d" "e" "f" "h" "i"
>
> Warning message:
> In mapply(function(a, b) a[b], example, ind) :
> longer argument not a multiple of length of shorter
> >
>
>
> On Fri, Jun 26, 2009 at 2:27 PM, Greg Hirson <ghirson at ucdavis.edu
> <mailto:ghirson at ucdavis.edu>> wrote:
>
> Dear list,
>
> I have two lists: one with data and one with TRUE/FALSE values for
> data I want to further analyze (see example below). I have been
> able to use a for loop to extract the data that I want to keep,
> but think that there probably exists a way to do it without a
> loop. Any ideas?
>
> #sample data
> set.seed(100)
> example = list(letters[1:10], letters[1:10], letters[1:10])
> ind = list(as.logical(sample(0:1, 10, rep=TRUE)),
> as.logical(sample(0:1, 10, rep=TRUE)), as.logical(sample(0:1, 10,
> rep=TRUE)), as.logical(sample(0:1, 10, rep=TRUE)))
>
> #loop method
> for (i in 1:length(example)) print(example[[i]][ind[[i]]])
>
> #result
> [1] "c" "g" "i"
> [1] "a" "b" "e" "f" "j"
> [1] "a" "b" "c" "d" "g" "h" "i"
>
>
> Thank you for the help.
>
> Greg
>
> --
> Greg Hirson
> ghirson at ucdavis.edu <mailto:ghirson at ucdavis.edu>
>
> Graduate Student
> Agricultural and Environmental Chemistry
>
> 1106 Robert Mondavi Institute North
> One Shields Avenue
> Davis, CA 95616
>
> ______________________________________________
> R-help at r-project.org <mailto: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
> <http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>
>
>
>
> --
> Jim Holtman
> Cincinnati, OH
> +1 513 646 9390
>
> What is the problem that you are trying to solve?
--
Greg Hirson
ghirson at ucdavis.edu
Graduate Student
Agricultural and Environmental Chemistry
1106 Robert Mondavi Institute North
One Shields Avenue
Davis, CA 95616
More information about the R-help
mailing list