-1

I have multiple .txt file pairs that look something like this:

file1_a.txt
file1_b.txt
file2_a.txt
file2_b.txt

They contain information that I want to analyse further with a function I have created. In the script, I need to analyse each file pair together (linked together by "file1" and "file2").

How would you use a for loop (or apply-family) to loop over each file pair, running the function for each of them?

The question is not quite he same as the one found here, as I am looking to work with file pairs.

In dummy code:

files <- list.files(pattern = "*.txt")

for(file_pairs in files){
  function(file1, file2)
}

The file_pairs part is what I am unsure about, as I do not know how to identify them and make it run on the files with similar name.

Haakonkas
  • 961
  • 9
  • 26
  • What precisely are you doing with these text files? I would assume that you want to read them into a data frame/table, but it is not entirely clear. – Tim Biegeleisen Feb 01 '18 at 14:03
  • When you write "script" I hope you mean "function". If not you need to fix that. Please provide a minimal reproducible example. – Roland Feb 01 '18 at 14:08
  • @TimBiegeleisen basically, i import their content to a variable (one for each file) and run them through a function. I want to do that for each file pair available in the folder. – Haakonkas Feb 01 '18 at 14:10

1 Answers1

1

Maybe something like this assuming the nomenclature of the files is consistent.

library(stringr)

files <- c('file1_a.txt', 'file1_b.txt', 'file2_a.txt','file2_b.txt')

unique.files <- unique(gsub('(.+)_[a-z].txt','\\1',files))

my.list <- vector('list',length(unique.files))
for(f in seq_along(unique.files)){
  files.sub <- str_detect(files, unique.files[f])
  files.to.do.stuff <- files[files.sub]
  my.list[[f]] <- files.to.do.stuff
}

my.list
#[[1]]
#[1] "file1_a.txt" "file1_b.txt"
#
#[[2]]
#[1] "file2_a.txt" "file2_b.txt"
Balter
  • 1,085
  • 6
  • 12