【问题标题】:Add date created column to multiple CSV files将创建日期列添加到多个 CSV 文件
【发布时间】:2019-08-22 23:56:52
【问题描述】:

我使用dir() 从一个不是我的工作目录的目录中获取我想要的 CSV。我想遍历每个文件并添加一个名为 "Date Created" 的列,并用首次制作 CSV 的日期填充所有行。我怎样才能做到这一点?

在我已经将文件合并到数据框之前,我尝试询问类似的问题,并且在取消嵌套所有文件之前尝试改变新列时出现错误。我觉得我的问题非常具体,这似乎是一种更好的替代方法。

【问题讨论】:

  • 你从哪里得到date the CSV was first made.的信息?
  • @RonakShah 我试图使用file.info()$ctime

标签: r dplyr data-manipulation


【解决方案1】:

Ronaks 的回答很到位。这是一个使用dplyr的示例

# using 'tidy' functions
library(dplyr)

# create example directory
temp_dir <- '~/test' 
dir.create(temp_dir)

# create example csvs (lapply just applies the function to each number)
lapply(1:3, 
       function(x) {
         # make file name
         temp_name <- file.path(temp_dir, paste0(x, '.csv'))
         # write data
         write.csv(x = data.frame(a = x),
                   file = temp_name)
         # sleep to get different created timestamps
         Sys.sleep(1)
       })

# check dir
dir(temp_dir, '.csv')
#> [1] "1.csv" "2.csv" "3.csv"

# read all and add Date Created
dir(temp_dir, '.csv', full.names = TRUE) %>% 
  lapply(function(x) {
    read.csv(x) %>% 
      # add date created column
      mutate(`Date Created` = file.info(x)$ctime)
  }) %>% 
  bind_rows()
#>   X a        Date Created
#> 1 1 1 2019-08-23 12:42:56
#> 2 1 2 2019-08-23 12:42:57
#> 3 1 3 2019-08-23 12:42:58

reprex package (v0.3.0) 于 2019 年 8 月 23 日创建

【讨论】:

    【解决方案2】:

    我们可以先在files中获取我们有兴趣读取的所有文件的路径,在file_time中获取它们各自的时间,然后使用Mapcbind新列Date_Created到他们各自的数据框。这将返回一个数据框列表。

    files <- list.files("/path/of/the/file", pattern = ".csv$", full.names = TRUE)
    file_time <- file.info(files)$ctime
    
    Map(cbind, lapply(files, read.csv), Date_Created = file_time)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2021-05-30
      • 2017-11-17
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多