1

assuming the simple code:

a <- list()
a[[1]] <- c(1,2,3)
a[[2]] <- c(2,3,4)

I want to ask about vector membership in the list and get the membership index. So for asking about c(1,2,3) I will get 1, and for asking about c(2,3,4) I will get 2. How do I do that?

Corel
  • 581
  • 3
  • 21

1 Answers1

2

An option is to either use setequal or all.equal (from base R) by looping through the list elements, return a logical index and wrap with which

f1 <- function(lstObj, vec) {
 which(sapply(lstObj, setequal, vec))
 }

f1(a, 1:3)
#[1] 1

f1(a, 2:4)
#[1] 2

Also, as @IceCreamToucan mentioned in the comments

f1n <- function(lstObj, vec){
   which(sapply(lstObj, function(x, y) isTRUE(all.equal(x, y)), vec))
 }

Another option is %in% with all

f2 <- function(lstObj, vec) {
     which(sapply(lstObj, function(x) all(x %in% vec)))
  }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Good answer. Small note: If order matters, f1 function definition would need to be `which(sapply(lstObj, function(x, y) isTRUE(all.equal(x, y)), vec))`. An example for which the results differ: `f1(list(c(2, 1, 3)), 1:3)` – IceCreamToucan Aug 13 '19 at 14:57
  • Isn't there a simpler solution? All this code just to ask if a vector is a member in the list?? Maybe a list is not the best way to go here in the sense of storing the vectors? – Corel Aug 13 '19 at 15:05
  • 1
    @Corel. If the `vector`s are of different lengths, a `list` would be appropriate. If it is not, you can have it as a `matrix` or `data.frame`. To check elements in a `list`, methods that can go inside the `list` would be useful. Either `lapply/sapply/mapply` are used (in different context though). Wrapping it inside a function is to make it simpler – akrun Aug 13 '19 at 15:07