【问题标题】:r extract element from the list with for-loopr 使用for循环从列表中提取元素
【发布时间】:2021-12-05 07:28:05
【问题描述】:

我有以下值列表:

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

【问题讨论】:

  • lapply(your_list,"[[",1) 可能会起作用。

标签: r for-loop


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这行得通吗:

    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"
    

    【讨论】:

      【解决方案3】:

      你可以使用 -

      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"
      

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 2020-08-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 1970-01-01
        相关资源
        最近更新 更多