list.files(path, pattern, full.names = TRUE)特定のディレクトリ内のファイルのリストを取得するために使用しています。
デフォルトでは、ファイルはアルファベット順にソートされています。Rで日付順に並べ替える方法はありますか?
list.files(path, pattern, full.names = TRUE)特定のディレクトリ内のファイルのリストを取得するために使用しています。
デフォルトでは、ファイルはアルファベット順にソートされています。Rで日付順に並べ替える方法はありますか?
このfile.info関数を使用して、ファイルの詳細を取得できます。これらの詳細を取得したら、それに応じてファイルを並べ替えることができます。例えば、
details = file.info(list.files(pattern="*.csv"))
とりわけ、変更および作成時間を含むデータフレームを提供します。そのデータフレームは好きなように並べ替えることができます。ここでは、変更時間に従って並べ替えますmtime。
details = details[with(details, order(as.POSIXct(mtime))), ]
files = rownames(details)
    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)
}