【问题标题】:Read multiple csv datasets with the date text from file name as new column使用文件名中的日期文本作为新列读取多个 csv 数据集
【发布时间】:2018-05-15 03:33:46
【问题描述】:

我有多个要导入 R 的 csv 文件。

如何将多个文件读入 R 并在第一列中添加包含文件名中的日期文本的列?

这里需要:

对于每个 csv 文件,获取文件名中的日期并将其添加为每个数据框的第一列,然后再绑定它们。

这是文件名中没有日期列的代码:

all <- lapply(c("file_10-16-2017.csv",
                "file_10-17-2017.csv",
                "file_10-18-2017.csv",
               function(x){
               read_csv(x, skip = 10)}) %>% bind_rows()

我希望我的最终结果看起来像这样:

Date_Pulled      Week         Date      spot1      Site ID test 
 10-16-2017  10/15/17   10/16/2017      trial          trial134
     .           .           .             .              .
     .           .           .             .              .
     .           .           .             .              .
 10-17-2017  10/15/17   10/16/2017      trial          trial134
     .           .           .             .              .
     .           .           .             .              .
     .           .           .             .              .

任何帮助都会很棒,谢谢!

【问题讨论】:

    标签: r csv readr


    【解决方案1】:

    我想出了另一种方法:

    filenames <- list.files(path = ".", pattern = NULL, all.files = FALSE, full.names = FALSE, recursive = FALSE, ignore.case = FALSE)
    
    read_csv_filename <- function(filenames){
      ret <- read.csv(filenames, skip = 10)
      ret$Source <- filenames #EDIT
      ret
    }
    
    import.list <- ldply(filenames, read_csv_filename)
    

    这应该可以解决问题

    【讨论】:

      【解决方案2】:

      首先,将所有要读取的文件放到一个单独的工作目录中,并将工作目录更改为这个。

      # 1. change wd
      setwd('new_file_path')
      
      # 2. get files from that directory
      my_files <- list.files()
      
      # 3. read in all files, skipping first 10 lines
      library(readr)
      dat_list <- lapply(my_files, read_csv, skip = 10)
      
      # 4. mutate a new column, which is the name of the file
      library(dplyr)
      dat_list_new <- lapply(dat_list, function(x) {
          mutate(x,
                 new_col_one = names(x))
      })
      
      # 5. port this list of data frames to the global environment
      names(dat_list_new) <- my_files # set the names of the dataframes
      list2env(dat_list_new,envir=.GlobalEnv)
      

      【讨论】:

      • 感谢您的帮助。有一个错误说,“mutate_impl(.data, dots) 中的错误:评估错误:找不到函数“名称”。”在第 4 步中。除了 readr 和 dplyr 之外,这是否需要不同的包?
      • 应该是names()
      • 是的,应该是names()。匆忙写了这篇,没有在数据上测试。这个答案应该会让你成功完成一半以上。
      • 您好,抱歉,在此之后出现另一个错误:“mutate_impl(.data, dots) 中的错误:new_col_one 列的长度必须为 13619(行数)或 1,而不是 42 " 我的数据集中有 42 列
      • 你是对的。我看到。这是因为您正在读取的文件数是 42,所以 names(x) 实际上给出了所有名称的向量。您需要当时正在运行的列表元素的名称。我实际上不确定如何即时执行此操作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-06
      相关资源
      最近更新 更多