Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract elements of a list in R?

Tags:

list

r

I have a list with several vectors which looks like this :

$`56`
[1] "OTU2998"             "UniRef90_A0A1Z9FS94" "UniRef90_A0A257ESC3"
[4] "UniRef90_A0A293NAV3" "UniRef90_A0A2E1NMU8" "UniRef90_A0A2E1NPX9"
[7] "UniRef90_A0A2E1NQL1" "UniRef90_A0A2E1NRD2" "UniRef90_X0UC66"    

$`57`
[1] "OTU3820"             "UniRef90_A0A1Z9H3N2" "UniRef90_A0A2D5I161"
[4] "UniRef90_A0A2E6PRN5"

$`58`
[1] "OTU4452"                "UniRef90_A0A1Z9KBI8"    "UniRef90_A0A2E1VTI6"   
[4] "UniRef90_A0A2G2KCN6"    "UniRef90_UPI000BFEC744"

$`59`
[1] "OTU0245"             "UniRef90_A0A1Z9MPM9" "UniRef90_A0A2E2ME98"
[4] "UniRef90_A0A2E8X9N7"

Is there a way to only extract the "OTUXXX" information? I mean, I would like to get something like this :

$`56`
[1] "OTU2998"       

$`57`
[1] "OTU3820"  

$`58`
[1] "OTU4452"   

$`59`
[1] "OTU0245" 

like image 448
Paillou Avatar asked Mar 04 '23 22:03

Paillou


1 Answers

We can loop through the list and extract the elements that match the substring 'OTU' at the beginning (^) of the string followed by four digits (\\d{4}) till the end ($) of the string with grepl

lapply(lst1, function(x) x[grepl("^OTU\\d{4}$", x)])
#$`56`
#[1] "OTU2998"

#$`57`
#[1] "OTU3820"

#$`58`
#[1] "OTU4452"

#$`59`
#[1] "OTU0245" "OTU1234"

NOTE: Using only base R methods


Or if we are a tidyverse aficionado, then use keep

library(tidyverse)
map(lst1, keep, str_detect, '^OTU\\d{4}$')

data

lst1 <-  list(
  `56` = c("OTU2998", "UniRef90_A0A1Z9FS94", "UniRef90_A0A257ESC3", "UniRef90_A0A293NAV3", "UniRef90_A0A2E1NMU8", "UniRef90_A0A2E1NPX9", "UniRef90_A0A2E1NQL1", "UniRef90_A0A2E1NRD2", "UniRef90_X0UC66"),
  `57` = c("OTU3820", "UniRef90_A0A1Z9H3N2", "UniRef90_A0A2D5I161", "UniRef90_A0A2E6PRN5"),
  `58` = c("OTU4452", "UniRef90_A0A1Z9KBI8", "UniRef90_A0A2E1VTI6", "UniRef90_A0A2G2KCN6", "UniRef90_UPI000BFEC744"),
  `59` = c("OTU0245", "UniRef90_A0A1Z9MPM9", "UniRef90_A0A2E2ME98", "UniRef90_A0A2E8X9N7", "OTU1234")
)
like image 83
akrun Avatar answered Mar 07 '23 00:03

akrun