[英]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.我想从一个文件夹中导入多个 CSV 文件,对它们运行一个函数,然后合并向量结果。
Currently I Am Importing The CSV Files Like This:目前我正在像这样导入 CSV 文件:
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.我确定有一种更简单的方法来使用 lapply 或其他东西。 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使用 tidyverse pkg,试试下面的
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, ...)
:您需要执行其余步骤,然后将结果与
lapply
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使用
pmap
函数
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.