For loop question in R

I hope that I can explain my question well enough to get an answer - any help would be appreciated.

I have a number if the data files that I need to merge into one. I use a for loop to do this and add a column that indicates which file it is.

In this case, each file contains 6 files with up to 100 data records.

When there are 6 files, I have no problem running this.

But when there is less, I have a problem.

What I would like to do is use a for loop to check files and use a for loop variable to build a vector that references existing files.

I can’t get the new variable to combine the new value of the for loop variable because it goes through the loop.

Here is an example of the code that I have written so far.

for ( rloop1 in 1 : 6) {
ReadFile=paste(rloop1,SampleName,"_",FileName,"_Stats.csv", sep="")
if (file.exists(ReadFile))
**files_found <- c(rloop1)**
}

, files_found , 1... 6 .

+3
3

, list.files(), . (. ?regex), .

n <- 6
Fnames <- paste(1:n,SampleName,"_",FileName,"Stats.csv",sep="")
Filelist <- Fnames[file.exists(Fnames)]

. paste file.exists , . for-loop.

( , ), :

gsub("^[:digit:]","", Filelist)

. ?regex

+4

, , , , . list.files - . , "_Stats.csv". , :

$ ls | grep Stats
bar_Stats.csv
foobar_Stats.csv
foobar_Stats.csv.txt
foo_Stats.csv

- csv, ( .txt ). list.files():

> list.files(pattern = "_Stats.csv$")
[1] "bar_Stats.csv"    "foo_Stats.csv"    "foobar_Stats.csv"

. - :

fnames <- list.files(pattern = "_Stats.csv$")
for(i in seq_along(fnames)) {
    assign(paste("file_", i, sep = ""), read.csv(fnames[i]))
}

file_1, file_2, file_3 .. . , lapply fnames:

lapply(fnames, read.csv)

, , do.call :

do.call(rbind, lapply(fnames, read.csv))
+7

I think there are better solutions (for example, you can use list.files()folders to scan and then cycle along the length of the returned object), but this should (I have not tried) do the trick (using your sample code):

files.found <- ""    
for (rloop1 in 1 : 6) {
    ReadFile=paste(rloop1,SampleName,"_",FileName,"_Stats.csv", sep="")
    if (file.exists(ReadFile)) files_found <- c(files.found, rloop1)
}

Alternatively, you can get the file names (except their index) with:

files.found <- ""    
for (rloop1 in 1 : 6) {
    ReadFile=paste(rloop1,SampleName,"_",FileName,"_Stats.csv", sep="")
    if (file.exists(ReadFile)) files_found <- c(files.found, ReadFile)
}

Finally, in your case, it list.filesmight look something like this:

files.found <- list.files(pattern = "[[:digit:]]_SampleName_FileName_Stats.csv")
+3
source

Source: https://habr.com/ru/post/1785855/


All Articles