【问题标题】:Can I automate an increasing value in a file name in R?我可以在 R 中自动增加文件名中的值吗?
【发布时间】:2020-05-03 19:52:39
【问题描述】:

所以我有需要修剪的 .csv 嵌套数据。我在 R 中编写了一系列函数,然后吐出了新的漂亮 .csv。问题是我需要使用 59 个 .csv 来执行此操作,并且我想自动化名称。

data1 <- read.csv("Nest001.csv", skip = 3, header=F)
functions functions functions
write.csv("Nest001_NEW.csv, file.path(out.path, edit), row.names=F)

那么...有什么方法可以让我将 Nest001 的名称循环到 Nest0059,这样我就不必删除并重新输入每个 .csv 的名称?

【问题讨论】:

标签: r loops csv


【解决方案1】:

编辑以纳入 Gregor 的建议:

一个选项:

filenames_in  <- sprintf("Nest%03d.csv", 1:59)
filenames_out <- sub(pattern = "(\\d{3})(\\.)", replacement = "\\1_NEW\\2", filenames_in)
all_files     <- matrix(c(filenames_in, filenames_out), ncol = 2)

然后循环遍历它们:

for (i in 1:nrow(all_files)) {
  temp <- read.csv(all_files[[i, 1]], skip = 3, header=F)
  do stuff
  write.csv(temp, all_files[[i, 2]], row.names = f)
)

要做到这一点purrr-style,你需要创建两个与上面类似的列表,然后编写一个自定义函数来读取文件,执行所有函数,然后输出它。

例如

purrr::walk2(
  .x = list(filenames_in),
  .y = list(filenames_out),
  .f = ~my_function()
)

.x.y 视为for 循环中的i;它同时遍历两个列表,并对每个项目执行功能。

更多信息请见here

【讨论】:

  • @Gregor--reinstateMonica-- 感谢您的关注!我会编辑帖子。
【解决方案2】:

最好的办法是将所有这些 CSV 文件放在一个文件夹中,而该文件夹中没有任何其他 CSV 文件。然后,您可以编写一个循环来遍历该文件夹中的每个文件,然后将它们读入。

library(dplyr)    

setwd("path to the folder with CSV's goes here")
combinedData = data.frame()
files = list.files()

for (file in files)
{
  read.csv(file)
  combinedData = bind_rows(combinedData, file)
}

编辑:如果文件夹中还有其他不想阅读的文件,可以添加这行代码只读取标题中包含“Nest”字样的文件:

files= files[grepl("Nest",filesToRead)]

我不记得是否区分大小写

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多