[英]R for loop to extract info from a file and add it into tibble?
我對 tidyverse 不是很好,所以如果這是一個簡單的問題,請原諒我。 我有一堆文件,其中包含我需要提取並添加到我創建的小標題中的不同列中的數據。
我希望行名以我設法創建的文件 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
這給了我一個清晰的 output 例如:
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 輸出,然后從中提取信息並將其放入一個小標題中。 我想我的第一個循環應該創建這些 sample_data 輸出,如下所示:
for (files in file.list()) {
>> get_domains <<
}
然后另一個循環從上述循環中提取該信息並將其插入到我的元數據小標題中。 有什么建議么? 非常感謝:PS,如果 R 中的常規數據幀對此更好,請告訴我。 我最近才了解到 tidyverse 是在 R 中組織數據幀的更好方法,但我必須了解更多信息。
你也可以這樣做:
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'))
我發現有時使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.