【问题标题】:R for loop to extract info from a file and add it into tibble?R for循环从文件中提取信息并将其添加到tibble?
【发布时间】:2021-05-21 16:26:39
【问题描述】:

我不太擅长 tidyverse,所以如果这是一个简单的问题,请原谅我。我有一堆文件,其中包含我需要提取并添加到我创建的 tibble 中不同列中的数据。

我希望行名以我设法创建的文件 ID 开头:

filelist <- list.fileS(pattern=".txt") # Gives me the filenames in current directory.
# The filenames are something like AA1230.report.txt for example

file_ID <- trimws(filelist, whitespace="\\..*") # Gives me the ID which is before the "report.txt"

metadata <- as_tibble(file_ID[1:181]) # create dataframe with IDs as row names for 180 files.

现在在这些报告文件中包含有关物种和丰度的信息(对于熟悉 kraken 的人来说,kraken 报告文件),我所需要的只是提取每个域的读取数。我可以使用以下内容轻松地在每个文件中搜索属于该域的域和读取次数:

sample_data <- as_tibble(read.table("AA1230.report.txt", sep="\t", header=FALSE, strip.white=TRUE))

sample_data <- rename(sample_data, Percentage=V1, Num_reads_root=V2, Num_reads_taxon=V3, Rank=V4, NCBI_ID=V5, Name=V6) # Just renaming the column headers for clarity

sample_data %>% filter(Rank=="D") # D for domain

这给了我一个清晰的输出,例如:

Percentage Num_Reads_Root Num_Reads_Taxon Rank  NCBI_ID Name     
       <dbl>          <int>           <int> <fct>   <int> <fct>    
1      75.9           60533              28 D           2 Bacteria 
2       0.48            386               0 D        2759 Eukaryota
3       0.01              4               0 D        2157 Archaea  
4       0.02             19               0 D       10239 Viruses  

现在,我只想获取第二列和最后一列中的信息,并将此信息保存到我的 tibble 中,这样我就可以得到如下内容:

> metadata
value     Bacteria_Counts    Eukaryota_Counts    Viruses_Counts     Archaea_Counts
<chr>     <int>              <int>               <int>               <int>
 1 AA1230  60533             386                 19                   4 
 2 AB0566
 3 AA1231
 4 AB0567
 5 BC1148
 6 AW0001
 7 AW0002
 8 BB1121
 9 BC0001
10 BC0002
....with 171 more rows

我只是想出一个 for 循环来创建这些 sample_data 输出,然后从中提取信息并将其放入 tibble 中。我想我的第一个循环应该创建这些 sample_data 输出,如下所示:

for (files in file.list()) {
  >> get_domains <<
}

然后另一个循环从上述循环中提取该信息并将其插入到我的元数据小标题中。 有什么建议么?非常感谢! PS:如果 R 中的常规数据帧对此更好,请告诉我,我最近才知道 tidyverse 是在 R 中组织数据帧的更好方法,但我必须了解更多。

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    你也可以这样做:

    library(tidyverse)
    filelist <- list.files(pattern=".txt") 
    nms <- c("Percentage", "Num_reads_root", "Num_reads_taxon", "Rank", "NCBI_ID", "Name")
    
    set_names(filelist,filelist) %>%
      map_dfr(read_table, col_names = nms, .id = 'file_ID') %>%
      filter(Rank == 'D') %>%
      select(file_ID, Name, Num_reads_root) %>%
      pivot_wider(id_cols = file_ID, names_from = Name, values_from = Num_reads_root) %>%
      mutate(file_ID = str_remove(file_ID, '.txt'))
    

    【讨论】:

    • 我试过了,但我得到了这个错误Column specification -------------------------------------------------------------------------------------------------- cols( Percentage = col_character(), Num_reads_root = col_character(), Num_reads_taxon = col_character(), Rank = col_character(), NCBI_ID = col_character(), Name = col_character() ) Error: Can't combine `Num_reads_taxon` &lt;character&gt; and `Num_reads_taxon` &lt;double&gt;. Run `rlang::last_error()` to see where the error occurred.
    • @CuriousDude 所以看起来你有不同的列类型。将在一分钟内编辑它
    • @CuriousDude 将 read_table 更改为 read.tablecol_names 更改为 col.names
    • 我进行了更改但收到此错误:Error in scan(file = file, what = what, sep = sep, quote = quote, dec = dec, : line 1 did not have 7 elements
    • @CuriousDude 你能不能尝试运行map_dfr(filelist, read.table, col.names = nms, sep='\t', header = FALSE, .id = 'file_ID') 这会导致错误吗?
    【解决方案2】:

    我发现有时使用 for 循环很不错,因为它可以保存一路上的所有进度,以防您遇到错误。然后你可以找到问题文件并调试它或使用try()但抛出warning()

    library(tidyverse)
    filelist <- list.files(pattern=".txt") #list files
    
    tmp_list <- list()
    for (i in seq_along(filelist)) {
      my_table <- read_tsv(filelist[i]) %>% # It looks like your files are all .tsv's
        rename(Percentage=V1, Num_reads_root=V2, Num_reads_taxon=V3, Rank=V4, NCBI_ID=V5, Name=V6) %>%
        filter(Rank=="D") %>%
        mutate(file_ID <- trimws(filelist[i], whitespace="\\..*")) %>%
        select(file_ID, everything())
      tmp_list[[i]] <- my_table
    }
    out <- bind_rows(tmp_list)
    out
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 2021-09-21
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多