Home > Back-end >  Subsetting one list based on another list and then finding position of the maxima
Subsetting one list based on another list and then finding position of the maxima

Time:02-11

UPDATED: I have two lists that look like this:

MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))

What I want to find are the positions in MyList2 of the maxima but only where the corresponding positions in MyList1 are >0. The result would be:

Result<-list(c(3),c())

To explain further where this result comes from, if you first subset the second list where MyList1>0 then you would have:

list(c(5,6,2),c(5,5,2))

The maximum element across both lists is 6 which only exists in list 1:

list(c(6),c())

The position of this in MyList2 are:

list(c(3),c())

I'm not sure of the best way to get to this desired result.

CodePudding user response:

Using mapply, you can do this:

m <- max(unlist(MyList2)[unlist(MyList1) > 0])
mapply(function(x,y) which(x == m & y > 0), MyList2, MyList1)

# [[1]]
# [1] 3
# 
# [[2]]
# integer(0)

With purrr::map2:

purrr::map2(MyList2, MyList1, function(x,y) which(x == m & y > 0))

#or 

purrr::map2(MyList2, MyList1, ~ which(.x == m & .y > 0))

data

MyList1<-list(c(0,1,1,1),c(1,1,2,0))
MyList2<-list(c(4,5,6,2),c(5,5,2,5))
  • Related