查找包含vector元素的列表对象

时间:2016-03-11 19:52:55

标签: r

我有一个向量列表。有没有办法在下面的设置中找到包含特定向量元素的列表对象?

示例数据:

> 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

预期输出:

>magicalstuff(7984)
[1] "ENSG00000050327"

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

谢谢!

4 个答案:

答案 0 :(得分:5)

例如:

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

答案 1 :(得分:5)

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"

答案 2 :(得分:3)

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

答案 3 :(得分:2)

一个神奇的功能:

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

magicalstuff(7984)
#[1] "ENSG00000050327"