Home > OS >  r extract element from the list with for-loop
r extract element from the list with for-loop

Time:10-19

I have the following list of values:

$`1`
[1] "S21_027_1"           "5_G3_A_1_counts.txt"

$`5`
[1] "S21_027_13"           "5_G3_A_12_counts.txt"

$`9`
[1] "S21_027_17"           "5_G3_A_15_counts.txt"

$`14`
[1] "S21_027_21"           "5_G3_A_22_counts.txt"

$`18`
[1] "S21_027_25"           "5_G3_A_26_counts.txt"

$`22`
[1] "S21_027_29"           "5_G3_A_29_counts.txt"

I try to extract only stuff which starts with S21_027.

I tried to use for loop however it keeps just one element.

My attempt to extract it:

order_column <- c()
for (i in length(order_col))
{
  v <- order_col[[i]][[1]]
  print(v)
  order_column <- c(v, order_column)
}

CodePudding user response:

Does this work:

lst <- list(c('S21_027_1','5_G3_A_1_counts.txt'),
            c('S21_027_13','5_G3_A_12_counts.txt'),
            c('S21_027_17','5_G3_A_15_counts.txt'))

sapply(lst, function(x) x[grepl('^S21_027', x)])
[1] "S21_027_1"  "S21_027_13" "S21_027_17"

CodePudding user response:

You may use -

library(purrr)
library(stringr)

map(order_col, str_subset, "S21_027")

#[[1]]
#[1] "S21_027_1"

#[[2]]
#[1] "S21_027_13"

#[[3]]
#[1] "S21_027_17"

Or to extract the 1st element -

map_chr(order_col, head, 1)
#[1] "S21_027_1"  "S21_027_13" "S21_027_17"
  • Related