【问题标题】:Merging of multiple excel files in R在R中合并多个excel文件
【发布时间】:2017-09-19 16:41:49
【问题描述】:

我在 R 中遇到了一个基本问题。我必须合并具有相同变量的相似数据类型的 72 个 excel 文件。我必须将它们合并到 R 中的单个数据集。我使用下面的代码进行合并,但这对于这么多文件似乎并不实用。谁能帮帮我?

data1<-read.csv("D:/Customer_details1/data-01.csv")

data2<-read.csv("D:/Customer_details2/data-02.csv")

data3<-read.csv("D:/Customer_details3/data-03.csv")

data_merged<-merge(data1,data2,all.x = TRUE, all.y = TRUE)

data_merged2<-merge(data_merged,data3,all.x = TRUE, all.y = TRUE)

【问题讨论】:

  • 如果我的解决方案有助于解决您的问题,您可以接受答案,以便我们关闭问题:)

标签: r


【解决方案1】:

首先,如果扩展名是 .csv,它们不是 Excel 文件,它们是 .csv 文件。

我们可以利用apply 系列函数来有效地做到这一点。

首先,让我们创建一个文件列表:

setwd("D://Customer_details1/")

#  create a list of all files in the working directory with the .csv extension
files <- list.files(pattern="*.csv")

在这种情况下,我们使用purrr::map,尽管我们也可以使用lapply - 更新为map_dfr 以消除对reduce 的需要,自动将rbind 写入数据框:

library(purrr)

mainDF <- files %>% map_dfr(read.csv) 

如果需要,您可以将其他参数传递给read.csvmap(read.csv, ...)

请注意,要使 rbind 起作用,列名必须相同,我假设它们是基于您的问题。

【讨论】:

  • 您可以使用map_df 并避免reduce 步骤。
  • 没问题,不过您似乎犯了一个小错字,列出了map_dfr 而不是map_df。您可能想修复它以免混淆任何人。
  • @beigel 不,如果您查看?purrr,您会发现map_dfrrbind 版本,map_dfccbind 版本。不过,查看基础公式 map_dfmap_dfr 的定义似乎完全相同(即使用 rbind),所以 map_df 也是正确的并没有错。
  • 我的错。 map_df 没有出现在文档中,而 map_dfrmap_dfc 出现了,所以我猜后两者是调用 map_ 的首选方式,因为它们更明确。
  • @aninditab 您是否同时安装了purrrdplyr
【解决方案2】:
#Method I
library(readxl)
library(tidyverse)
path <- "C:/Users/Downloads"
setwd(path)
fn.import<- function(x) read_excel("country.xlsx", sheet=x)
sheet = excel_sheets("country.xlsx")
data_frame = lapply(setNames(sheet, sheet),  fn.import )
data_frame = bind_rows(data_frame, .id="Sheet")
print (data_frame)
#Method II
install.packages("rio")
library(rio)
path <- "C:/Users/country.xlsx"
data <- import_list(path , rbind=TRUE) 

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2019-03-29
  • 2012-04-29
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 2015-07-26
相关资源
最近更新 更多