简体   繁体   中英

Import Multiple CSV Files, Run A Function, Then Combine Results Into A Dataframe In R

I Want To Import Multiple CSV Files From A Single Folder Run A Function On Them, and Combine The Vector Results.

Currently I Am Importing The CSV Files Like This:

Arbys.Data <- read.csv("~/Desktop/CSV Restaurant Data/MR - ARBYS.csv")
BJs.Data <- read.csv("~/Desktop/CSV Restaurant Data/MR - BJS RESTERAUNT 
& BREWERY.csv")
Bojangles.Data <- read.csv("~/Desktop/CSV Restaurant Data/MR - BOJANGLES 
FAMOUS CHICKEN N BISCUITS.csv")

Running Them Thru My Function Individually

Arbys <- My.Function(Arbys.Data) 
BJs <- My.Function(BJs.Data) 
Bojangles <- My.Function(Bojangles.Data) 

Then Combining The Results Into A Dataframe Like This

RP<-rbind.data.frame(Arbys,BJs,Bojangles)

Im Certain There Is An Easier Way To Use lapply Or Something. I Tried Running Code Like This

filenames<- list.files("~/Desktop/CSV Restaurant Data/", pattern ="*.csv")
list.df <- lapply(filenames, read.csv)
Data<-My.Function(list.df)

Data.Frame<- rbind.data.frame(Data)

But The Result Is Not Producing What I Want.

Use tidyverse pkg, try the below

Data <- dir(path="~/Desktop/CSV Restaurant Data/",pattern = "*.csv",include.dirs = TRUE, full.names = TRUE)%>%
map(read_csv) %>%    # map :: read_csv() from the readr package
reduce(rbind)        # reduce :: with rbind into one dataframe
str(Data) 

You are almost there. you need to lapply for the rest of the steps and then combine the results with do.call(rbind, ...) :

Data<-lapply(list.df, My.Function)

Data.Frame<- do.call(rbind, Data)

Should be pretty simple.

setwd("C:/your_path_here")
fnames <- list.files()
csv <- lapply(fnames, read.csv)
result <- do.call(rbind, csv)

use pmap function

require(purrr)
flist <- c('~/Desktop/CSV Restaurant Data/MR - ARBYS.csv', '~/Desktop/CSV Restaurant Data/MR - BJS RESTERAUNT & BREWERY.csv', '~/Desktop/CSV Restaurant Data/MR - BOJANGLES FAMOUS CHICKEN N BISCUITS.csv')
data.list <- pmap(list(flist), function(fname) {
  f <- read.csv(fname)
  r <- My.Function(f)
  return(r)
})
as.data.frame(bind_rows(data.list))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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