简体   繁体   English

合并R中的多个excel文件

[英]Merging of multiple excel files in R

I am getting a basic problem in R. I have to merge 72 excel files with similar data type having same variables.我在 R 中遇到了一个基本问题。我必须合并72 个 excel具有相同变量的相似数据类型的文件。 I have to merge them to a single data set in R. I have used the below code for merging but this seems NOT practical for so many files.我必须将它们合并到 R 中的单个数据集。我使用下面的代码进行合并,但这对于这么多文件来说似乎不实用。 Can anyone help me please?谁能帮帮我吗?

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)

First, if the extensions are .csv, they're not Excel files, they're .csv files.首先,如果扩展名是 .csv,则它们不是 Excel 文件,而是 .csv 文件。

We can leverage the apply family of functions to do this efficiently.我们可以利用apply系列函数来有效地做到这一点。

First, let's create a list of the files:首先,让我们创建一个文件列表:

setwd("D://Customer_details1/")

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

Let's use purrr::map in this case, although we could also use lapply - updated to map_dfr to remove the need for reduce , by automatically rbind -ing into a data frame:在这种情况下,让我们使用purrr::map ,尽管我们也可以使用lapply - 更新到map_dfr来消除对reduce的需要,通过自动rbind -ing 到数据帧中:

library(purrr)

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

You can pass additional arguments to read.csv if you need to: map(read.csv, ...)如果需要,您可以将其他参数传递给read.csvmap(read.csv, ...)

Note that for rbind to work the column names have to be the same, and I'm assuming they are based on your question.请注意,要使rbind工作,列名必须相同,我假设它们是基于您的问题。

#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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM