首页 > 解决方案 > 将创建日期列添加到多个 CSV 文件

问题描述

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

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

标签: rdplyrdata-manipulation

解决方案


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 包(v0.3.0)于 2019 年 8 月 23 日创建


推荐阅读