find_latest: Find latest version of a file

Description Usage Arguments Details Author(s) See Also Examples

View source: R/find_latest.R

Description

If some file names include dates, this function will find the latest version of a given file. This can be handy e.g. for finding the latest data update automatically. find_latest scans recursively a directory, looking for file names matching a given pattern (or regular expression) and including dates. Dates are extracted using extract_date, using a user-provided parser (see details). The full path to the most recent file will be returned.

Usage

1
2
3
4
5
6
7
find_latest(
  pattern,
  where = getwd(),
  date_parser = lubridate::ymd,
  quiet = FALSE,
  ...
)

Arguments

pattern

a character string indicating the name of the file to look for, or regular expression to be matched against file names

where

the directory in which to look for the file; defaults to the current directory

date_parser

a function to extract dates from character strings; we recommend using lubridate's function there, e.g. ymd (any date format with year, month, day) or dmy (any format using day, month, year); defaults to lubridate::ymd

quiet

a logical indicating if messages should be displayed (TRUE, default), or not (FALSE)

...

further arguments passed to list.files

Details

The date parser used by default is lubridate::ymd, so that any date specified as year/month/day (regardless of the separator used) should work. One exception is that only dates provided as numbers can be used e.g. "1982.02.04" and "82/2/4" are okay but not "1982 Feb 04". For dates provided in a different order, check other parsers implemented in lubridate, e.g. lubridate::dmy for day-month-year formats, or lubridate::ydm for year-day-month. Note that parsers for date-time objects can also be used, but in any case a Date object will be returned.

Author(s)

Thibaut Jombart

See Also

extract_date to extract dates from character strings; see the lubridate website and cheatsheet for other parsers

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
 

if (require(reportfactory)) {

## create random factory and toy files
odir <- getwd()
f <- new_factory(path = tempdir())

file.create(file.path("data", "linelist_2020-10-01.xlsx"))
file.create(file.path("data", "linelist_2020-10-12.csv"))
file.create(file.path("data", "linelist.xlsx"))
file.create(file.path("data", "contacts.xlsx"))
file.create(file.path("data", "death_linelist_2020-10-13.xlsx"))

## find the latest data with 'linelist' in the name; note that this
## matches both 'linelist' and 'death_linelist' files
find_latest("linelist")

## same, but this time files starting with 'linelist', i.e. excluding
## 'death_linelist'
find_latest("^linelist")

## this returns NULL
find_latest("foobar")

## cleanup
unlink(f, recursive = TRUE)
setwd(odir)
}

reconhub/rfextras documentation built on Aug. 16, 2021, 5:25 a.m.