Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: Problem involving subsetting one list based on another list and then finding position of the maxima

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading