how to read multiple (loop) .csv files with a date name in R?

元气小坏坏 提交于 2019-12-12 04:47:27

问题


I have several .csv files with these names (from 1 January 2016 to 31 december 2016)

    01012016.csv
    02012016.csv
    ...
    31122016.csv

I want to use read.csv( by using a loop but still considering date patterns.

start<-as.Date("01-01-16")
end<-as.Date("31-12-16")
theDate<-start
­{read.csv(theDate,".csv")}

回答1:


You can get the names of all the files using list.files and giving it the path of all folder where all the files are located:

filenames = list.files('/path/to/datefiles/', pattern = "*.csv")

Then you can use lapply to iterate over the vector 'filenamescontaining the names of files and applyread.csvto each of them and set additional parameters likeheaderandstringsAsFactors` as TRUE or FALSE as required:

data = lapply(filenames,read.csv,header = TRUE,stringsAsFactors=FALSE)



回答2:


To create a character vector containing the format yyyymmdd you could try:

(yyyymmdd.vec <- format(seq(from = as.Date("01-01-16", format = "%d-%m-%y"),
                            to = as.Date("31-12-16", format = "%d-%m-%y"), 
                            by = "day"), format=  "%Y%m%d"))


来源:https://stackoverflow.com/questions/46079790/how-to-read-multiple-loop-csv-files-with-a-date-name-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!