Nuwansiri Wijesinghe
Nuwansiri Wijesinghe

Reputation: 11

Select specific csv file according to their file name In R

I work with R language . I have 8031 csv files and file name of first file is Mean_SST_1997-12-31 and every file name has a pattern the only change is the date. The dates range from 1997.12.31 to 2019.12.31 and every single day has a csv file. What i need to do is i need to select files for sfecific month for example february . Can anyone help me ?

Upvotes: 1

Views: 618

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

Pull in the files, extract and parse the dates, and then select the ones you want:

library(lubridate)

# get the file  names
# use whatever directory or regex you need, see `?list.files` for help
files = data.frame(fn = list.files(pattern = "Mean_SST_.*"))

# pull everything after the last `_` and 
# convert it to date in year/month/day order
files$date = ymd(sub(".*_", "", files$fn))

# select the files you want based on date and read them in
feb_data = lapply(files[month(files$date) == 2, "fn"], read.csv)

Upvotes: 1

Related Questions