Filter a list in R based on character vector or data frame?

Viewed 428

I have been struggling with this for hours now. I have a list containing sequences of DNA. I am unsure how to produce a reproducible example, but this is how the str(mylist) looks.

> str(mylist)
List of 10
 $ Zotu1 : chr [1:427] "T" "G" "G" "G" ...
 $ Zotu2 : chr [1:402] "T" "G" "G" "G" ...
 $ Zotu3 : chr [1:402] "T" "G" "G" "G" ...
 $ Zotu4 : chr [1:427] "T" "G" "G" "G" ...
 $ Zotu5 : chr [1:427] "T" "G" "G" "G" ...

The full list contains 4434 list elements. I only want to keep 2436 of these before I continue data analysis. I can't figure out how to filter this list based on the names of the list (i.e. Zoutu1, Zotu2, ...).

I currently have an excel sheet containing all the names I want to keep. I can transform these into a character vector, data-frame etc. But how I could use these to filter the list I just can't figure out...

str(zOTUs_keep)

'data.frame':   2436 obs. of  1 variable:
$ zOTUs_keep: chr  "Zotu1" "Zotu10" "Zotu100" "Zotu1000" ...

> names(mylist)
   [1] "Zotu1"    "Zotu2"    "Zotu3"    "Zotu4"    "Zotu5"    "Zotu6"    "Zotu7"   
   [8] "Zotu8"    "Zotu9"    "Zotu10"   "Zotu11"   "Zotu12"   "Zotu13"   "Zotu14"  
  [15] "Zotu15"   "Zotu16"   "Zotu17"   "Zotu18"   "Zotu19"   "Zotu20"   "Zotu21"  
  [22] "Zotu22"   "Zotu23"   "Zotu24"   "Zotu25"   "Zotu26"   "Zotu27"   "Zotu28"  
  [29] "Zotu29"   "Zotu30"   "Zotu31"   "Zotu32"   "Zotu33"   "Zotu34"   "Zotu35"  
  [36] "Zotu36"   "Zotu37"   "Zotu38"   "Zotu39"   "Zotu40"   "Zotu41"   "Zotu42" 

I have tried the list.filter function from rlist, but this does not seem to work because I don't have any names in the list to filter on.

Does anyone have any suggestions? Thank you in advance! :)

1 Answers

Just extract the column as a vector and use it to extract the list elements by name

mylist2 <- mylist[zOTUs_keep$zOTUs_keep]
Related