Home > Net >  How to find the index of a specific character in a list of lists?
How to find the index of a specific character in a list of lists?

Time:11-12

I have a list of lists as such:


[[989]]
[1] "ARP5" "AGF" 

[[990]]
[1] "CDT6" "AngX"

[[991]]
[1] "TD26" "RIFL"

[[992]]
[1] NA

[[993]]
[1] "SPH1"

[[994]]
[1] "FAP87"  "CFAP87"

I would like to query this list to get the index where the gene == "FAP87".

In this case the index would be 994.

Unlist does not work because it changes the index number.

list %in% "FAP87" does not work unless the length of the sublist == 1. (for example, list %in% "SPH1" does give me the index 993).

How can I access the index where "FAP87" is present in a list of lists?

CodePudding user response:

Use a loop

which(sapply(list, function(x) "FAP87" %in% x))

Or another option is enframe (from tibble) to a two column dataset, filter the rows and pull the name column (which will be the sequence value as the list is unnamed)

library(tibble)
library(dplyr)
library(tidyr)
enframe(list) %>% 
   unnest(value) %>%
   filter(value %in% 'FAP87') %>%
   pull(name)
  • Related