如何通过创建函数来读取多个CSV文件 [英] How to read multiple CSV files by creating function

查看:173
本文介绍了如何通过创建函数来读取多个CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写一个读取多个 csv 文件的函数,其中许多文件以00开头,例如 001.csv 002.csv 003.csv

我的代码是:

pre $ getmonitor< - 函数(id,directory,summarize = FALSE){

文件名< - list.files(pattern =specdata / .csv)

data< - read .csv(paste(directory)/,id,.csv,sep =))
return(data)
}
pre
$ b $ p

它可以工作,如果你输入:

$ p $ get $ c $ getmonitor(100, specdata)

但如果输入:

  getmonitor(001,specdata)

将返回:

$ p $ 文件错误(文件,rt):无法打开连接


$ b

另外:警告信息:

 在文件(文件rt)中:
不能打开文件'specdata / 1.csv':没有这样的文件或目录

如何让函数读取 csv 以<$开头的文件你可以使用 sprintf 00 s?

解决方案 / code>来格式化这样的数字:

 > sprintf('%03d',12)
[1]012


How do you write a function that reads multiple csv files, many of them starting with 00, e.g. 001.csv, 002.csv, 003.csv and so on.

My code is:

getmonitor <- function(id, directory, summarize = FALSE) {

  filename <- list.files(pattern="specdata/.csv")

  data <- read.csv( paste(directory,"/",id,".csv",sep="") )
  return (data) 
}

It works if you type:

getmonitor(100, "specdata")

but if I type:

getmonitor(001, "specdata")

it will return:

Error in file(file, "rt") : cannot open the connection

In addition: Warning message:

In file(file, "rt") :
  cannot open file 'specdata/1.csv': No such file or directory

How do I make my function read csv files that start with 00s?

解决方案

You can use sprintf to format numbers like this:

> sprintf('%03d',12)
[1] "012"

这篇关于如何通过创建函数来读取多个CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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