编写脚本以读取许多具有相似文件名的.csv文件 [英] Writing a script for reading many .csv files with similar filenames

查看:115
本文介绍了编写脚本以读取许多具有相似文件名的.csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个文件名相似的.csv文件,除了数字月份(即03_data.csv,04_data.csv,05_data.csv等),我想读入R.

I have several .csv files with similar filenames except a numeric month (i.e. 03_data.csv, 04_data.csv, 05_data.csv, etc.) that I'd like to read into R.

我有两个问题:

  • R中是否有类似于 MATLAB的varname和assignin 让我创建/声明一个变量名 在一个函数或循环中,这将使我能够 读取相应的.csv文件-即 将03_data.csv转换为03_data data.frame, 等等.?我想写一个快速循环 这样做是因为文件名是 相似.
  • 作为替代方案, 用第一个创建一个数据框 文件,然后使用 循环?我该怎么办?
  • Is there a function in R similar to MATLAB's varname and assignin that will let me create/declare a variable name within a function or loop that will allow me to read the respective .csv file - i.e. 03_data.csv into 03_data data.frame, etc.? I want to write a quick loop to do this because the filenames are similar.
  • As an alternative, is it better to create one dataframe with the first file and then append the rest using a for loop? How would I do that?

推荐答案

您可以查看

You could look at this related question. You can create the file names easily with a paste command:

file.names <- paste(sprintf("%02d",1:10), "_data.csv", sep="")

一旦有了文件名(无论是通过创建文件名还是通过在其他问题中从目录中读取文件名),就可以快速导入文件:

Once you have your file names (whether by creating them or by reading them from the directory as in the other question), you can import them quickly with an lapply:

import.list <- lapply(file.names, read.csv)

最后,要将列表合并到一个数据帧中,最简单的方法是使用下面的reshape函数:

Lastly, to combine the list into one dataframe, the easiest approach is to use the reshape function below:

library(reshape)
data <- merge_recurse(import.list)

这篇关于编写脚本以读取许多具有相似文件名的.csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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