I am writing a function which would get all files from a particular directory and then execute some commands on those files that match my criteria. One of the criteria is that the file should not have the name “test.csv”, and the other that it shouldn’t be a png-file. Now, the thing with test.csv works fine, but I don’t get R to ignore png-files, so unfortunately my script does not work as long as there are any png-files in the working directory. Here is an extract from my function:
file_list = list.files()
for (file in file_list){
if ((file != "test.csv") & (grep(".*png", file) != 1)){
my.file <- read.table(file)
}
}
I’ve tried all kinds of variations of the grep command like grep(".*png", file) == 0, length(grep(".*png", file)) < 1 and similar things, but nothing worked. Any ideas what’s going wrong?
How about using
grepl, which returns a logical as to whether the pattern appears in the string in question:I’d also change the regular expression to specifically look for “.png” at the end of the file name, using
".*\\.png$"So your code could be changed to