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



我有以下值列表:

$`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"

我尝试只提取以S21_027开头的东西。

我尝试使用for循环,但是它只保留一个元素。

我试图提取它:

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

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

可以吗?

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"

您可以使用-

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"

或者提取第一个元素-

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

最新更新