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"
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}$')
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")
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With