R 如何提取文件名中的日期并对其排序以查找最新的文件?
我目前在一个文件夹中有几个文件。它包含股票的每日更新。看起来是这样的R 如何提取文件名中的日期并对其排序以查找最新的文件?,r,date,xlsx,R,Date,Xlsx,我目前在一个文件夹中有几个文件。它包含股票的每日更新。看起来是这样的 Onhand Harian 12 Juli 2019.xlsx Onhand Harian 13 Juli 2019.xlsx Onhand Harian 14 Juli 2019.xlsx... and so on. 我想使用文件名上的日期只读取最新的excel文件。如何做到这一点?thanx提前如果您的所有文件都包含相同的名称,您可以这样做 #List all the file names in the folder f
Onhand Harian 12 Juli 2019.xlsx
Onhand Harian 13 Juli 2019.xlsx
Onhand Harian 14 Juli 2019.xlsx... and so on.
我想使用文件名上的日期只读取最新的excel文件。如何做到这一点?thanx提前如果您的所有文件都包含相同的名称,您可以这样做
#List all the file names in the folder
file_names <- list.files("/path/to/folder/", full.names = TRUE)
#Remove all unwanted characters and keep only the date
#Convert the date string to actual Date object
#Sort them and take the latest file
file_to_read <- file_names[order(as.Date(sub("Onhand Harian ", "",
sub(".xlsx$", "", basename(file_names))), "%d %B %Y"), decreasing = TRUE)[1]]
#列出文件夹中的所有文件名
文件名我会这样做:
library(stringr)
library(tidyverse)
x <- c("Onhand Harian 12 Juli 2019.xlsx",
"Onhand Harian 13 Juli 2019.xlsx",
"Onhand Harian 14 Juli 2019.xlsx")
lookup <- set_names(seq_len(12),
c("Januar", "Februar", "März", "April", "Mai", "Juni", "Juli",
"August", "September", "Oktober", "November", "Dezember"))
enframe(x, name = NULL, value = "txt") %>%
mutate(txt_extract = str_extract(txt, "\\d{1,2} \\D{3,9} \\d{4}")) %>% # September is longest ..
separate(txt_extract, c("d", "m", "y"), remove = FALSE) %>%
mutate(m = sprintf("%02d", lookup[m]),
d = sprintf("%02d", as.integer(d))) %>%
mutate(date = as.Date(str_c(y, m, d), format = "%Y%m%d")) %>%
filter(date == max(date)) %>%
pull(txt)
# "Onhand Harian 14 Juli 2019.xlsx"
库(stringr)
图书馆(tidyverse)
九月最长。。
分离(txt_提取,c(“d”,“m”,“y”),删除=假)%>%
mutate(m=sprintf(“%02d”,lookup[m]),
d=sprintf(“%02d”,作为.integer(d)))%>%
变异(日期=as.date(str_c(y,m,d),format=“%y%m%d”))%>%
筛选器(日期==最大(日期))%>%
拉动(txt)
#“现有Harian 14 Juli 2019.xlsx”
月份名称是德语吗?鉴于最新的excel文件对应于具有最新创建日期的文件,您还可以查看创建时间而不是文件名:files@JorisChau太好了。thanx会返回c(NA,NA,NA)
,因为他的语言环境显然是德语。您知道如何将设为.Date
以理解德语月份名称吗?@January From?strtime
,%B-当前区域设置中的完整月份名称。
所以我认为%B
已经基于用户的区域设置工作了?对不起,我应该说:因为他的文件名显然是德语的。我们不知道他的地点是什么。因此,Nicodemus,如果此解决方案不起作用,请尝试Sys.setlocale(locale=“de_de.utf8”)
@NicodemusSigitSutanto。如果语言环境已经是印度尼西亚语,则无需更改该语言环境。@Ronaksha我已经应用了您的代码,但调用的文件是第一个创建的文件。如何更改它,以便调用最新创建的文件?塔克斯