File Import in R - Taking only part of the name

Asked

Viewed 253 times

3

To with a local file xlsx, only that the file name is random (changes date and time at the end of the file name), and wanted to know if you can read the file only by the beginning of the name.

Follow 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. There’s a way I can just pick it up at the beginning instead of taking the whole file name?

  • 1

    Look at my answer, please. I think it’s much simpler than yours :).

2 answers

2


The easiest way is with the argument pattern of 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 circumflex to tell the regular expression engine that you should 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

0

I managed to solve with the following command:

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

:)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.