简体   繁体   中英

Selecting multiple elements from list of matrix that match elements of list of vector

I have two variables, one is a list of matrices and the other is a list of vectors.

people: load("https://dl.dropboxusercontent.com/u/22681355/a.Rdata")

mat: load("https://dl.dropboxusercontent.com/u/22681355/b.Rdata")

I would like to go from [[1]] to [[99]] along the elements in people and select the rows in mat where the first column of mat matches people and return the second column of mat .

I tried:

lapply(seq_along(people), function(i) mat[mat[,1,i] == 
    people[i], 2, i]) 

However this cannot handle the fact that sometimes there is only 1 matching entry while in other cases there can be 2 or three matching entries.

Can someone help with modifying my code?

Small example:

People:

[[1]]
[1] 34 56 7
[[2]]
[1] 13 93
[[3]]
[1] 42

Mat

,,1
    [,1] [,2] [,3]
[1,] 34   **2**    1
[2,] 56   **2**    1
[3,] 7    **2**    2

,,2
    [,1] [,2] [,3]
[1,] 9    2    1
[2,] 13   **2**    1
[3,] 71   2    2

,,3
    [,1] [,2] [,3]
[1,] 90   2    1
[2,] 1    2    1
[3,] 42   **2**    2

The output would be:

I'm not sure if this is pulling out what you want. From your comment i am matching the elements of people[1] with mat[,,1], people[2] with mat[,,2] and so on and returning the value in the second column of mat if there id a match.

I have used the first 3 values from your people and mat Rdata.

# Reduce problem
# mat <- mat[,,1:3]
#people <- people[1:3]

# Data
mat <- structure(c(82, 59, 6, 1, 1, 2, 1, 1, 2, 17, 51, 18, 1, 2, 1, 
               1, 2, 1, 31, 26, 40, 1, 1, 1, 1, 1, 1), .Dim = c(3L, 3L, 3L))

people <- list(6, 51, c(31, 26, 40))


l <- lapply(seq(people), function(x) {
            lapply(people[x] , function(z) {
                   mat[,,x][,2][match(z, mat[,,x][,1])]
       })})


#--------------------------------------------------------------------

# output
R> mat
, , 1

     [,1] [,2] [,3]
[1,]   82    1    1
[2,]   59    1    1
[3,]    6    2    2

, , 2

     [,1] [,2] [,3]
[1,]   17    1    1
[2,]   51    2    2
[3,]   18    1    1

, , 3

     [,1] [,2] [,3]
[1,]   31    1    1
[2,]   26    1    1
[3,]   40    1    1

R> people
[[1]]
[1] 6

[[2]]
[1] 51

[[3]]
[1] 31 26 40

R> l
[[1]]
[[1]][[1]]
[1] 2


[[2]]
[[2]][[1]]
[1] 2


[[3]]
[[3]][[1]]
[1] 1 1 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM