user1471980 user1471980 - 1 year ago 81
R Question

how do you extract date from the file name in R?

I have to read files in a directory and extract the dates from the file names.

filenames <- list.files(path="C:/Downloads/vmstat", pattern="*vmstat*", full.names=TRUE)

filenames like this:


I need to extract
from this filename and assign it to a variable like
. How could I extract the date from the filenames?

Answer Source

We can use gsub to match the substring that are not date and replace it with blanks ("")

gsub("^[^0-9]+\\.|\\.[A-Za-z]+$", "", filenames)
#[1] "2016.11.22"

Or extract the basename and then convert to Date class with lubridate

#[1] "2016-11-22"


filenames <- "C:/Downloads/vmstat/vmstat.2016.11.22.Tue"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download