【问题标题】:Read multiple csv files in several directories in r在r中的几个目录中读取多个csv文件
【发布时间】:2018-10-29 16:37:06
【问题描述】:

我想从不同的目录中读取多个 .csv 文件,然后将其放入单个数据帧中。

我有两种目录要读取:

E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Austria/Ap deo/Variant/Ap_deo_1.csv

E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Austria/Ap deo/Variant/Ap_deo_2.csv


E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Austria/Bar soap/Variant/Bar_soap_1.csv


E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Austria/Bar soap/Variant/Bar_soap_2.csv

E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Switzerland/Ap deo/Variant/Ap_deo_1.csv

E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Switzerland/Ap deo/Variant/Ap_deo_2.csv

E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Switzerland/Bar soap/Variant/Bar_soap_1.csv


E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/Switzerland/Bar soap/Variant/Bar_soap_2.csv

所以上面的目录我有,所以我必须根据我将在路径中给出的路径读取所有文件,如路径奥地利或瑞士... bar soap 每个国家有 8 个类别我只想读取变体文件夹 csv 所以这些 csv 文件可以是 1 或 2 或 3 或有时更多我如何阅读这些文件?

【问题讨论】:

标签: r csv fread


【解决方案1】:

可能类似于以下内容。

base <- "E:/R_Process/R_Input_UDM/Greater Europe/CEW Hub/"
or1 <- "(Austria|Switzerland)"
or2 <- "(Ap deo|Bar soap)"

pat <- paste(or1, or2, "Variant/.*\\.csv$", sep = "/")

filenames <- list.files(path = base, pattern = pat, 
                        recursive = TRUE, full.names = TRUE)

df_list <- lapply(filenames, read.csv)
names(df_list) <- sapply(filenames, basename)

【讨论】:

  • CEW HUB 应该是可变的,就像有 4-5 个中心一样,它包含不同的国家,这些国家可能包含不同的类别,如牙膏、漱口水、手动 TB,因为有多个中心,所以有多个部门也像大欧洲一样,还有拉丁美洲和亚洲,我该如何改变这些?
  • @ShantamMalgaonkar 在答案中有两个 OR 运算符 | 的例子。如果您需要匹配多个替代字符串,只需执行this|that|etc
【解决方案2】:

我已经创建了这个函数

https://gist.github.com/Lightbridge-AI/1c5740782a63317b8516ef4fe007e256

它可以从一个目录中读取多个CSV并将其放入数据框列表中。

# No arg: default path = current working directory
read_dir_csv()

# Give a directory path
read_dir_csv(dir_path)

# Also, can read from every sub-directory of given directory
read_dir_csv(dir_path, recursive = T) 

在您有多个目录路径的情况下,您可能希望遍历每个路径。 可以试试这样的。

all_path <- c(path1, path2, path3 , ...)

ls <- purrr::map(all_path, read_dir_csv) 

但是,在您的情况下,ls 是一个列表列表。您必须先转换为 DF 列表。

ls_of_df <- purrr::flatten(ls)

然后,要将ls_of_df 转换为单个DF,您可以使用dplyr::bind_rows()dplyr::bind_cols()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    相关资源
    最近更新 更多