使用rbind将多个.csv文件加载到R中的单个数据帧中的问题 [英] Issue in Loading multiple .csv files into single dataframe in R using rbind
问题描述
我写了以下函数来组合300个.csv文件。我的目录名是specdata。我已经执行了以下步骤,
步骤1:
> x < - function(directory){
dir< - directory
data_dir< - paste(getwd(),dir,sep =/)
files< - list.files(data_dir,pattern ='\\.csv')
表< - lapply(paste(data_dir,files,sep = /),read.csv,header = TRUE)
污染物< - do.call(rbind,tables)
}
步骤2:
> x (specdata)
步骤3:
> head(pollutantmean)
污染物):没有找到对象污染物。
我对此做了什么错误。
在你的函数中有很多不必要的代码。您可以将其简化为:
load_data< - function(path){
files< - dir ,pattern ='\\.csv',full.names = TRUE)
tables< - lapply(files,read.csv)
do.call(rbind,tables)
}
污染物质< - load_data(specdata)
do.call
+ rbind
相对较慢。您可能会发现 dplyr :: bind_rows
或 data.table :: rbindlist
要快得多。
I have written the following function to combine 300 .csv files.My directory name is "specdata". I have done the following steps for execution,
step 1:
> x <- function(directory) {
dir <- directory
data_dir <- paste(getwd(),dir,sep = "/")
files <- list.files(data_dir,pattern = '\\.csv')
tables <- lapply(paste(data_dir,files,sep = "/"), read.csv, header = TRUE)
pollutantmean <- do.call(rbind , tables)
}
step 2:
>x("specdata")
step 3:
>head(pollutantmean)
Error in head(pollutantmean) : object 'pollutantmean' not found
What is the mistake I have done into this . Can you please anyone explain ?
Thanks in Advance.
There's a lot of unnecessary code in your function. You can simplify it to:
load_data <- function(path) {
files <- dir(path, pattern = '\\.csv', full.names = TRUE)
tables <- lapply(files, read.csv)
do.call(rbind, tables)
}
pollutantmean <- load_data("specdata")
Be aware that do.call
+ rbind
is relatively slow. You might find dplyr::bind_rows
or data.table::rbindlist
to be substantially faster.
这篇关于使用rbind将多个.csv文件加载到R中的单个数据帧中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!