Вам просто нужно правильно установить свои данные. Перемещение файлов в соответствующие папки является тривиальным. Смотрите комментарии в коде.
# create some fake data
cat("2017-01-01", file = "2017-01-01.txt")
cat("2018-05-11", file = "2018-05-11.txt")
cat("2018-09-09", file = "2018-09-09.txt")
# fetch all files - here I'm using to find exact dates and your method may vary
xy <- list.files(pattern = "\\d{4}-\\d{2}-\\d{2}\\.txt")
# prepare variables that will create (sub)folders
# having things in Date form makes extraction of year easy (and safe)
xy <- data.frame(file = xy, date = as.Date(gsub("\\.txt", "", xy)), stringsAsFactors = FALSE)
xy$path <- sprintf("./%s/%s", format(xy$date, "%Y"), xy$date)
# check that folder(s) exist
subfolders <- as.character(unique(xy$path))
# create those that do not exist
cs <- xy[!sapply(subfolders, FUN = dir.exists), ]
# if there's no data, it means all appropriate folders are already created
if (nrow(cs) == 0) {
message("All folders already exist.")
} else {
sapply(cs$path, dir.create, recursive = TRUE)
}
# prepare paths where to move files to
xy$dest_to <- sprintf("%s/%s", xy$path, xy$file)
# execute the final move
mapply(FUN = function(x, y) {
message(sprintf("Moving file %s to %s", x, y))
file.rename(from = x, to = y)
}, x = xy$file, y = xy$dest_to)