[R] selecting vector elements using matrices and combining the results
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Jul 28 19:36:36 CEST 2009
Try this:
> lapply(1:3, function(i) cbind(v1, v2)[cbind(col(m1)[i,], (m1+2*m2)[i,])])
[[1]]
[1] "A" "b" "D" "f"
[[2]]
[1] "C" "E"
[[3]]
[1] "D" "e"
On Tue, Jul 28, 2009 at 12:48 PM, Jean V Adams<jvadams at usgs.gov> wrote:
> I've been scratching my head over this one for too long. I'm hoping
> someone out there can solve this riddle.
>
> I have two vectors of characters, v1 and v2, both of length L, and two
> matrices of logicals, m1 and m2, both of dimension N*L. The first matrix
> of logicals corresponds to the first vector of characters, and the second
> to the second.
>
> The matrices are telling me which of the elements of v1 and v2 are
> selected, and for each of the L elements either a value from v1 is
> selected, a value from v2 is selected, or neither is selected (but both
> are never selected). So, the two matrices never have a TRUE in the same
> place, i.e., m1 + m2 yields a matrix of 0s and 1s (no 2s).
>
> What I would like to end up with is a list of length N, that has the
> selected elements of v1 and v2 meshed together in their original order.
>
> Here's an example (using much smaller N and L than in my real data):
>
> v1 <- LETTERS[1:6]
> v2 <- letters[1:6]
>
> m1 <- matrix(c(T, F, F, T, F, F, F, F, T, F, T, F, F, F, F, T, F, F),
> byrow=T, ncol=6)
> m2 <- matrix(c(F, T, F, F, F, T, F, F, F, F, F, F, F, F, F, F, T, F),
> byrow=T, ncol=6)
>
> v1
> v2
> m1
> m2
> m1+m2
>
> Given these two vectors and two matrices, I want to end up with this list:
>
> result <- list(c("A", "b", "D", "f"), c("C", "E"), c("D", "e"))
> result
>
> I'm using R for Windows version 2.9.0.
>
> Thanks for your help.
>
> Jean
>
>
> `·.,, ><(((º> `·.,, ><(((º> `·.,, ><(((º>
>
> Jean V. Adams
> Statistician
> U.S. Geological Survey
> Great Lakes Science Center
> 223 East Steinfest Road
> Antigo, WI 54409 USA
> phone: 715-623-4190, ext. 3125
> FAX: 715-623-6773
> GLSC web site: http://www.glsc.usgs.gov
> e-mail: jvadams at usgs.gov
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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