Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a file into R with partly unknown filename

Tags:

r

Is there a way to read a file into R where I do not know the complete file name. Something like.

read.csv("abc_*")

In this case I do not know the complete file name after abc_

like image 264
Kunal Batra Avatar asked Feb 18 '23 08:02

Kunal Batra


1 Answers

If you have exactly one file matching your criteria, you can do it like this:

read.csv(dir(pattern='^abc_')[1])

If there is more than one file, this approach would just use the first hit. In a more elaborated version you could loop over all matches and append them to one dataframe or something like that.

Note that the pattern uses regular expressions and thus is a bit different from what you did expect (and what I wrongly assumed at my first shot to answer the question). Details can be found using ?regex


If you have a directory you want to submit, you have do modify the dir command accordingly:

read.csv(dir('path/to/your/file', full.names=T, pattern="^abc"))

The submitted path in your case may be c:\\users\\user\\desktop, and then the pattern as above. full.names=T forces dir() to output a whole path and not only the file name. Try running dir(...) without the read.csv to understand what is happening there.


If you want to give your path as a complete string, it again gets a bit more complicated:

filepath <- 'path/to/your/file/abc_'
read.csv(dir(dirname(filepath), full.names=T, pattern=paste("^", basename(filepath), sep='')))

That process will fail if your filename contains any regular expression keywords. You would have to substitute then with their corresponding escape sequences upfront. But that again is another topic.

like image 75
Thilo Avatar answered Feb 21 '23 16:02

Thilo