简体   繁体   中英

r extract element from the list with for-loop

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)
}

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"

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"

Using base R

 lapply(order_col, grep, pattern = 'S21_027', value = TRUE)
[[1]]
[1] "S21_027_1"

[[2]]
[1] "S21_027_13"

[[3]]
[1] "S21_027_17"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM