Search positions of elements in array using two lists

Viewed 263

I have an array like this:

arr1<-array(1:5,dim=c(3,4,2))

And two lists like these:

li1<-list(1,2)
 
li2<-list(list(c(2,3)),list(c(1,2)))

#length(li1)==length(li2)

I want to check in the first (according to first element of li1) matrix of the array were I can find '1' in the rows 2 and 3 (according to first element of li2). I want also to check in the second matrix of the array (according to second element of li1) were I can find '1' in the rows 1 and 2 (according to second element of li2). And so on (if I had more elements in li1 and li2). The position of element '1' should be the corresponding column were the element can be found. I can (almost) do that individually for each element of the lists.

f1 <- function(x) {which(arr1[x, , li1[[1]]] == 1)}
result <- lapply(li2[[1]], f1)

But I would like to do the same to n elements of li1 and li2, using an 'apply()' function. I'm struggling with that and trying different 'apply' combinations.

The result should be something like this:

> result
[[1]]
[1] 4 2

[[2]]
[1] 2 0 
1 Answers

This is my own intricate, primitive and unpolished solution:

df1<-t(data.frame(li2))

f1 <- function(x,y) {which(arr1[x, ,y] == 1)}

for (i in 1:2){
print(mapply(f1,df1[i,],i))
}
Related