Reputation: 1
I am trying to write a for
loop that will grab information from each successive file in a folder and then paste this info into a data.frame
. The file names only change by their year. As it stands, the for
loop seems to be unable to move on to the next year and instead fills the data frame with first year's information only. I have set a working directory to the folder that contains all of the years. What command will change the year in the path name for each iteration of the loop, as in:
for (year in 2001:2011) {
2001,2001+1, 2001+2, 2001+3, etc.
}
Thanks!
Upvotes: 0
Views: 99
Reputation: 887691
Or you can use lapply
. Using @nrussell example data. I named the files as 2006.csv
, 2007.csv
etc. in my working directory
list.files(pattern="2\\d+.csv") #I used pattern argument as I have other files in the working directory which I don't want to read
#[1] "2006.csv" "2007.csv" "2008.csv" "2009.csv" "2010.csv"
lst <- lapply(list.files(pattern="2\\d+.csv"),
function(x) read.csv(x, header=TRUE, sep=""))
lst[1:2]
[[1]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
[[2]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
Upvotes: 2
Reputation: 18612
There are a few ways to go about this, but here's one approach. Say I have a directory of files called TempDir
, which contains the files
> list.files("F:/TempDir")
[1] "tempFile_2006.csv" "tempFile_2007.csv" "tempFile_2008.csv" "tempFile_2009.csv" "tempFile_2010.csv"
having the common root name tempFile_
, followed by a year. Then you could selectively read in certain files into a list of data.frame
s using something like this:
Years <- 2007:2010
dfList <- list(NULL)
length(dfList) <- length(Years)
##
for(i in 1:length(Years)){
iPath <- paste0("F:/TempDir/tempFile_",Years[i],
".csv")
dfList[[i]] <- read.csv(
file=iPath,
header=TRUE)
dfList
}
##
This gives me the following list of data.frame
s:
> dfList
[[1]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
[[2]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
[[3]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
[[4]]
X x y
1 1 1 6
2 2 2 7
3 3 3 8
4 4 4 9
5 5 5 10
I wrote the same data to each of these files, but obviously if they contained different data sets the data.frame
s in the list
would not be identical.
Upvotes: 3