本文介绍了通过文件名称将多个.csv文件导入到R.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含332个.csv文件的文件夹,从001.csv到332.csv。它们具有相同的标题。
如果我想从文件(其名称从a.csv到b.csv)计算对象的平均值。如何将文件a,a + 1,a + 2,... b中的数据合并到数据帧?
示例:输入5:130;
处理:从文件005.csv,006.csv,007.csv,...,130.csv读取数据,然后将它们合并到数据帧中。

I have a folder that contains 332 .csv files, from 001.csv to 332.csv. They have the same header.If I want to calculate the mean of an object from the files (its names is from a.csv to b.csv). How can I merge data in file a,a+1,a+2,...b into a dataframe?Example: Input 5:130;Process: reading data from files 005.csv, 006.csv, 007.csv, ..., 130.csv then merging them in a dataframe.

推荐答案

假设你有一个文件夹中的所有 .csv 文件,以下函数将给你所需要的:

Supposing you have all the .csv files in one folder, the following function will give you what you need:

# defining the function
merged <- function(id = 1:332) {
  df <- data.frame()
  for(i in 1:length(id)){
    add <- read.csv(as.character(paste0(sprintf("%03s",id[i]),".csv")))
    df <- rbind(df,add)
  }
  colnames(df) <- c(..specify the colnames in here..)
  assign("dat", df, envir = .GlobalEnv)
}

# getting your merged df
merged(5:130)

合并的数据帧现在位于数据帧 dat

The merged dataframes are now in the dataframe dat

这篇关于通过文件名称将多个.csv文件导入到R.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 00:11