简体   繁体   English

r 使用for循环从列表中提取元素

[英]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.我尝试仅提取以 S21_027 开头的内容。

I tried to use for loop however it keeps just one element.我尝试使用 for 循环,但它只保留一个元素。

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使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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