1

我在这里已经有一个类似的问题: R - 如何按文件名中的日期选择文件?

但我必须做一点改变。

我仍然有一个文件名列表,类似于:

list = c("AT0ACH10000700100dymax.1-1-1993.31-12-2003",
         "AT0ILL10000700500dymax.1-1-1990.31-12-2011", 
         "AT0PIL10000700500dymax.1-1-1992.31-12-2011",
         "AT0SON10000700100dymax.1-1-1990.31-12-2011",
         "AT0STO10000700100dymax.1-1-1992.31-12-2006",  
         "AT0VOR10000700500dymax.1-1-1981.31-12-2011",
         "AT110020000700100dymax.1-1-1993.31-12-2001",
         "AT2HE190000700100dymax.1-1-1973.31-12-1994", 
         "AT2KA110000700500dymax.1-1-1991.31-12-2010", 
         "AT2KA410000700500dymax.1-1-1991.31-12-2011")

我已经有一个命令可以整理出具有一定记录长度的文件(例如本例中的 10 个):

#Listing Files (creates the list above)
files = list.files(pattern="*00007.*dymax", recursive = TRUE)

#Making date readable
split_daymax = strsplit(files, split=".", fixed=TRUE)

from = unlist(lapply(split_daymax, "[[", 2))
to = unlist(lapply(split_daymax, "[[", 3))
from = as.POSIXct(from, format="%d-%m-%Y")
to = as.POSIXct(to, format="%d-%m-%Y")

timelistmax = difftime(to, from, "days")

#Files with more than 10 years of recording
index = timelistmax >= 10*360
filesdaymean = filesdaymean[index]

我现在的问题是我有太多文件,没有计算机可以处理。

现在我只想读入包含 1993 年(或我想要的任何其他特定年份)的文件的文件,并且从那时起有 10 年的录音,所以录音应该至少到 2003 年。

所以不应该包含 1973-1994 的文件,但是 1981-2011 的文件是可以的。

在这种情况下,我不知道如何选择年份。

我很感谢任何帮助

4

2 回答 2

1
library(stringr)
library(lubridate)
fileDates <- str_extract_all(files, "[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}")

find_file <- function(x, whichYear, noYears = 10) {
  start <- as.Date(x[[1]], "%d-%m-%Y")
  end <- as.Date(x[[2]], "%d-%m-%Y")
  years <- as.numeric(end-whichYear, units = "days")/365
  years > noYears & (year(start) <= year(whichYear) & 
                       year(end) >= year(whichYear))
}
sapply(fileDates, find_file, whichYear = as.Date("1993-01-01"), noYears = 10)

您有两个条件,您可以首先计算自 1993 年以来的年数,然后使用布尔逻辑来确定 1993 年是否在日期范围内。

于 2018-01-10T17:21:22.553 回答
1

使用files,tofrom正如您在上面定义的那样,这应该会为您提供包含 1993 年至 2003 年之间至少十年跨度数据的文件:

library(lubridate)
df <- data.frame(file_name = files, file_start = from, file_end = to)
df_index <- year(df$file_start) <=1993 & year(df$file_end) >= 2003
files_to_load <- df$file_name[df_index]

如果需要仅基数的解决方案,请将 POSIXct 转换为 POSIXlt 并提取年份组件,如下所示:

df <- data.frame(file_name = files, 
                 file_start = as.POSIXlt(from), 
                 file_end = as.POSIXlt(to))

df_index <- (df$file_start$year+1900 <=1993 & 
             df$file_end$year+1900  >= 2003)

files_to_load <- df$file_name[df_index]
于 2018-01-10T17:22:09.580 回答