在 R 中,我希望在文件夹中找到最新的 xlsx 文件,然后从该文件导入数据

In R I wish to find the latest xlsx file in a folder and then import the data from that file

在 R 中,我希望在文件夹中找到最新的 xlsx 文件,然后从该文件导入数据。所有文件都具有相同的格式。我只是一直空白。请告知正确的代码。

CompanyFileNames <- file.info(list.files 
                              (path = "Y:/...Data", 
                               pattern = "*port.xlsx", 
                               full.names = T))

CompanyFilelatest <- subset(CompanyFileNames, mtime == max(mtime))

CompanyFilelatest <- CompanyFilelatest[0]

Companymonthly <- sapply(CompanyFilelatest, 
              read_excel, simplify=FALSE) 
              %>% bind_rows(.id = "id")                         

write.csv(Companymonthly, "Companymonthly.csv")

你需要的是最新文件的文件路径,存储为CompanyFilelatest的rowname。使用 rownames() 提取文件路径,然后这应该可以工作。

CompanyFileNames <- file.info(list.files 
                              (path = getwd(), 
                                pattern = "*.xlsx", 
                                full.names = T))

CompanyFilelatest <- subset(CompanyFileNames, mtime == max(mtime))

CompanyFilelatest <- rownames(CompanyFilelatest) # use rownames not subseting with 0

Companymonthly <- sapply(CompanyFilelatest, 
                         read_excel, simplify=FALSE) %>% bind_rows(.id = "id")                         

write.csv(Companymonthly, "Companymonthly.csv")