【发布时间】: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 中组织数据帧的更好方法,但我必须了解更多。
【问题讨论】: