使用rbind将多个.csv文件加载到R中的单个数据帧中的问题 [英] Issue in Loading multiple .csv files into single dataframe in R using rbind

查看:214
本文介绍了使用rbind将多个.csv文件加载到R中的单个数据帧中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下函数来组合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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆