Wow. Thank you so much for this solution. Just FYI, I also found a solution which is as follows:
# get a list of all .tsv files in the directory
blast_files <- list.files(pattern = "\\.tsv$")
# loop through each file and read it into a data frame
blast_dfs <- lapply(blast_files, function(file) {
read.table(file, header = FALSE, sep = "\t", stringsAsFactors = FALSE,
col.names = c("query_id", "subject_id", "pct_identity", "alignment_length",
"mismatches", "gap_opens", "q_start", "q_end", "s_start", "s_end",
"evalue", "bit_score"))
})
# combine all data frames into one
blast_df <- do.call(rbind, blast_dfs)
# find duplicate hits and remove them
dup_rows <- duplicated(blast_df[c("query_id", "subject_id")]) | duplicated(blast_df[c("query_id", "subject_id")], fromLast = TRUE)
blast_df <- blast_df[!dup_rows, ]
# find reverse duplicates and remove them
rev_dup_rows <- which(blast_df$subject_id %in% blast_df$query_id & blast_df$query_id %in% blast_df$subject_id)
blast_df <- blast_df[-rev_dup_rows[seq(2, length(rev_dup_rows), by = 2)],]
# output the unique hits to a new file
unique_df <- unique(blast_df)
write.table(unique_df, file = "unique_hits.tsv", sep = "\t", quote = FALSE,
row.names = FALSE, col.names = FALSE)