Question

I would to apply a loop in R to process several files, one file per time. The files have exactly the same pattern, just the string "...split1..." is a crescent number to my files. Then a have files like "...split1...", "...split2..." ... "...split777...". I want output files like in the same logic, in the example: "newsplit1.txt", "newsplit2.txt" ... "newsplit777.txt".

all <- read.table("nsamplescluster.split1.adjusted", header=TRUE, sep=";") all <- all[, -grep("GType", colnames(all))] write.table(all, "newsplit1.txt", sep=";")

Cheers!

Was it helpful?

Solution

Use loop and paste file names.

for(i in 1:777){
    infile <- paste0("nsamplescluster.split",i,".adjusted")
    outfile <- paste0("newsplit",i,".txt")
    all <- read.table(infile, header=TRUE, sep=";")
    all <- all[, -grep("GType", colnames(all))]
    write.table(all, outfile, sep=";")
}

OTHER TIPS

If the files are all in the same directory, you can also use

 filenames<- list.files(your.directory, pattern="nsamplescluster")

This will create a vector with all file names in your.directory with the indicated pattern. You can then use this to loop over your files. For instance,

 for(i in filenames){
 do stuff
 }

This may come in handy if the number of files change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top