r - 将创建日期列添加到多个 CSV 文件
问题描述
我曾经dir()
从不是我的工作目录的目录中获取我想要的 CSV。我想遍历每个文件并添加一个名为的列"Date Created"
,并用首次制作 CSV 的日期填充所有行。我怎样才能做到这一点?
在我已经将文件合并到数据框之前,我尝试询问类似的问题,并且在取消嵌套所有文件之前尝试改变新列时出现错误。我觉得我的问题非常具体,这似乎是一种更好的替代方法。
解决方案
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 日创建
推荐阅读
- javascript - chrome.notifications.onClosed 未执行
- amazon-web-services - 如何将值赋予在模板的堆栈中创建的参数?
- vim - 遍历vim中的taglist
- python - Pyflink get_gateway() 方法不起作用
- python-2.7 - Slurm 无法调用 Pytorch
- r - 在R中保存用dendextend修改的树状图
- lua - 我在我的代码中找不到问题,你看到了吗?
- java - Intellij Mac 中的 JavaFx 编码错误
- python - 在 for 循环中创建嵌套字典
- angular-cli - 运行“ng -v”会产生错误:“未知错误:SyntaxError: Unexpected token 'export'”