Mussa
Mussa

Reputation: 117

Creating a loop for several input files at once

I have an R code

example.bed.file <- paste0(
    path.package("SeqKat"),
    "/extdata/LP6005334_DNA_H01.bed"
    );

seqkat(
    5,
    3.2,
    2,
    bed.file = example.bed.file,
    output.dir = ".",
    chromosome = "all",
    ref.dir = example.ref.dir,
    chromosome.length.file = example.chromosome.length.file
    );

This code demands an input file which here is LP6005334_DNA_H01.bed

I 63 input files all with .bed and different names

I want to have a loop to work over my input files without needing to put them one by one and run the code

Thank you for any help

Upvotes: 0

Views: 336

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388797

I don't know what the functions that you have used return and their types but in general the approach you should take is write a function that works for one file.

read_file <- function(x) {
  example.bed.file <- paste0(path.package("SeqKat"),x)
  
  seqkat(5,3.2,2,
    bed.file = example.bed.file,
    output.dir = ".",
    chromosome = "all",
    ref.dir = example.ref.dir,
    chromosome.length.file = example.chromosome.length.file)
}

Now create a vector of all the file names that you want to read, you can do that using list.files which will collect all the files that end with '.bed' extension and pass the function that you wrote to it using lapply.

file_names <- list.files(pattern = '\\.bed', full.names = TRUE)
result <- lapply(file_names, read_file)

Upvotes: 1

esperaporque
esperaporque

Reputation: 55

Here is some starter code, you should be able to get it from here

path <- "directorypath"
files <- dir(path)
#read.csv as an example
result <- rep(NA, length(files))
for(i in 1:length(files){
file <- files[i]
result[i] <- read.csv(file)
}

Upvotes: 0

Related Questions