I have many csv files in a folder and their names are in the same format ending with a date (xys 01.12.2017). I need to add the date to each data in the first column. I found many examples to do that but in all examples files have same the column format. However my files do not contain same number of columns. Is it possible to add the date even the columns numbers vary? Appreciate your help in advance.
Asked
Active
Viewed 1,105 times
-4
-
1It's easier to help if you can provide some sort of [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output. You said you tried to use some code -- what exactly did you try and how exactly did it fail to meet your need. – MrFlick Dec 07 '17 at 20:47
1 Answers
0
If all of the files are in a specific subdirectory you can list the files, and then use an apply()
function to read the data and add the date as the first column.
# list the files
fileList <- list.files(...,full.names=TRUE)
theDataFrames <- lapply(fileList,function(x) {
data <- read.csv(x,header=TRUE)
# extract all characters after 'xls' in 'xys01.01.2017'
date <-rep(substr(x,4,nchar(x)),nrow(data))
# bind date to data frame and return
cbind(date, data)
})

Len Greski
- 10,505
- 2
- 22
- 33