29

list.files(path, pattern, full.names = TRUE)用来获取特定目录中的文件列表。

默认情况下,文件按字母顺序排序。R中有什么方法可以让它们按日期排序吗?

4

2 回答 2

60

您可以使用该file.info功能获取文件的详细信息。获得这些详细信息后,您可以相应地对文件进行排序。例如,

details = file.info(list.files(pattern="*.csv"))

给出一个数据框,其中包含修改和创建时间。您可以根据需要对该数据框进行排序。这里我按照修改时间排序,mtime

details = details[with(details, order(as.POSIXct(mtime))), ]
files = rownames(details)
于 2012-12-07T11:51:38.963 回答
1

请注意,您也可以按accessed time或排序creation time
这是一个方便的并行函数,可以处理您喜欢的任何内容。

sort_files_by_date <- function(folder_path = '.', search_pattern = NULL, by = 'mtime'){

require(furrr)
require(magrittr)
require(stringr)
require(tidyverse)

  if (!by %>% str_detect('^(m|a|c)time$')) {
    stop('Argument `by` must be one of "mtime", "atime", or "ctime".')
  }

  file_names <-

    # Gets all the file paths for a given path and pattern
    list.files(path = folder_path, pattern = search_pattern, full.names = TRUE) %>%

    # Turns into a one-column tibble (see below)
    tibble(file_names = .)

  files_by_datetime <-

    suppressWarnings(
      future_map_dfr(
        .x = file_names,
        .f = file.info,
        .progress = TRUE,
        extra_cols = FALSE # passed to file.info for performance boost
      )
    ) %>%

    # gets expanded file info, then select the last-modified time and last-accessed time
    select(mtime, atime, ctime) %>%

    # reintroduce our original 'file_names'
    bind_cols(file_names) %>%

    # arrange by descending time (depending on the users choice)
    arrange(
      desc(
        case_when(
          (by == 'mtime') ~ mtime,
          (by == 'atime') ~ atime,
          (by == 'ctime') ~ ctime
        )
      )
    )

  return(files_by_datetime)

}
于 2020-03-26T03:39:47.217 回答