jatha
jatha

Reputation: 934

Finding list object that contains vector element

I have a list of vectors. Is there any way to find list object(s) that contain a particular vector element in the setting below?

Example data:

> head(mylist)
$ENSG00000049449
[1]   5954 440034

$ENSG00000050327
[1]      7984 102725117

$ENSG00000072195
[1]     29904 100996693

$ENSG00000091262
[1]       368 105369239

$ENSG00000100031
[1]      2678     91227     92086    728441 102724197

$ENSG00000103319
[1]     29904 101930123

Expected output:

>magicalstuff(7984)
[1] "ENSG00000050327"

>magicalstuff(29904)
[1] "ENSG00000072195" "ENSG00000103319"

Thanks!

Upvotes: 3

Views: 72

Answers (4)

Pierre L
Pierre L

Reputation: 28441

A magical function:

magicalstuff <- function(x) {
  ind <- unlist(lapply(mylist, `%in%`, x=x))
  names(mylist)[ind]
}

magicalstuff(7984)
#[1] "ENSG00000050327"

Upvotes: 2

Stefan Jansson
Stefan Jansson

Reputation: 109

mylist <-
  structure(
    list(
      ENSG00000049449 = c(5954, 440034),
      ENSG00000050327 = c(7984,102725117),
      ENSG00000072195 = c(29904, 100996693),
      ENSG00000091262 = c(368,105369239),
      ENSG00000100031 = c(2678, 91227, 92086, 728441, 102724197),
      ENSG00000103319 = c(29904, 101930123)
    ),
    .Names = c(
      "ENSG00000049449", "ENSG00000050327", "ENSG00000072195",
      "ENSG00000091262", "ENSG00000100031", "ENSG00000103319"
    )
  )

names(mylist[grep("7984", mylist) ])
#> [1] "ENSG00000050327"

names(mylist[grep("29904", mylist) ])
#> [1] "ENSG00000072195" "ENSG00000103319"

Upvotes: 5

TJGorrie
TJGorrie

Reputation: 396

findme <- function(value, object){
names(object)[sapply(object, function(x) value %in% x)]
}
#> findme(2678, mylist)
#[1] "ENSG00000072195"

Upvotes: 3

DatamineR
DatamineR

Reputation: 9618

For example:

names(mylist)[(unlist(lapply(mylist, function(x) 29904 %in% x)))]
[1] "ENSG00000072195" "ENSG00000103319"

Upvotes: 5

Related Questions