File Import in R - Taking only part of the name

3

With a local xlsx file, only the file name is random (it changes the date and time at the end of the file name), and was wondering if you can read the file just by the beginning of the name.

The following is the file name:

df = read_excel("report-R041-20181016102502.xlsx")

For example, the beginning of it: report-R041 does not change. It will always be that name. Is there any way I can get it from scratch instead of getting the whole file name?

    
asked by anonymous 24.10.2018 / 14:29

2 answers

2

The easiest way is with the argument pattern of the functions list.files or dir .

As the files are in another directory, first switch to it.

old_dir <- setwd("C:/tmp/")

fich1 <- list.files(pattern = "^report-R041")
fich2 <- dir(pattern = "^report-R041")

identical(fich1, fich2)    # TRUE

In the pattern I added the caret to tell the regular expression engine to look at the beginning of the word.

Now, after processing (or just after reading) the files you can go back to the old directory.

setwd(old_dir)    # Repor o estado do sistema
    
24.10.2018 / 17:30
0

I was able to resolve with the following command:

setwd("C:/tmp/")
vetor = grep("report-R041", dir(), value = T)
df041 = readxl::read_xlsx(vetor [length(vetor)], skip = 7)

:)

    
24.10.2018 / 14:47