【问题标题】:Read in CSV files and Add a Column with File name读入 CSV 文件并添加带有文件名的列
【发布时间】:2022-01-30 15:07:18
【问题描述】:

假设您有 2 个文件,如下所示。

file_1_october.csv
file_2_november.csv

文件具有相同的列。所以我想阅读R 中的两个文件,我可以很容易地用map 来完成。我还想在每个读取文件中包含一个带有文件名的列month。例如,对于file_1_october.csv,我想要一个名为“月”的列,其中包含“file_1_october.csv”字样。

为了重现性,假设 file_1_october.csv

name,age,gender
james,24,male
Sue,21,female

而 file_2_november.csv 是

name,age,gender
Grey,24,male
Juliet,21,female

我想读取这两个文件,但在每个文件中都包含一个与文件名相对应的月份列,以便我们拥有;

name,age,gender,month
james,24,male, file_1_october.csv
Sue,21,female, file_1_october.csv

name,age,gender,month,
Grey,24,male, file_2_november.csv,
Juliet,21,female, file_2_november.csv

【问题讨论】:

    标签: r csv dplyr tidyverse


    【解决方案1】:

    也许是这样的?

    csvlist <- c("file_1_october.csv", "file_2_november.csv")
    
    df_list <- lapply(csvlist, function(x) read.csv(x) %>% mutate(month = x))
    
    for (i in seq_along(df_list)) {
      assign(paste0("df", i), df_list[[i]])
    }
    

    这两个数据框将保存在df1df2中。

    【讨论】:

    • 谢谢。很多本森我有一个精神障碍。这行得通。
    • 我确实接受了你的回答。谢谢。
    【解决方案2】:

    这是一个(大部分)tidyverse 替代方案,可避免循环:

    library(tidyverse)
    
    csv_names <- list.files(path = "path/", # set the path to your folder with csv files
                            pattern = "*.csv", # select all csv files in the folder
                            full.names = T) # output full file names (with path)
    # csv_names <- c("file_1_october.csv", "file_2_november.csv")
    
    csv_names2 <- data.frame(month = csv_names, 
                             id = as.character(1:length(csv_names))) # id for joining
    
    data <- csv_names %>% 
      lapply(read_csv) %>% # read all the files at once
      bind_rows(.id = "id") %>% # bind all tables into one object, and give id for each
      left_join(csv_names2) # join month column created earlier
    

    这提供了一个数据对象,其中包含来自所有 CSV 的数据。如果您单独需要它们,您可以省略bind_rows() 步骤,为您提供多个表的列表(“tibbles”)。然后可以使用list2env() 或一些split() 函数拆分它们。

    【讨论】:

      猜你喜欢
      • 2017-04-21
      • 1970-01-01
      • 2017-05-17
      • 2018-08-31
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多