[R] Reading in files with variable parts to names
ba208 at exeter.ac.uk
Thu Mar 26 20:03:35 CET 2009
If your directory contains only files you want to load anyway, then
list.files() is your friend,
> list.files(pattern = "comp") # or pattern =".asc" for example
If you do need to create the names manually, then you could create the
combinations with expand.grid, as in,
> do.call(paste, as.list(expand.grid(x = seq(1950,1960), y = 1:10))) #
> you'll want to tweak paste to suit your needs
On 26 Mar 2009, at 18:40, Steve Murray wrote:
> Dear all,
> I'm trying to read in a whole directory of files which have two
> variable parts to the file name: year and month. E.g. comp198604.asc
> represents April of 1986 - 'comp' is fixed in each case. Years range
> between 1986 to 1995 and months are between 1 and 12.
> Just to be clear, there are 12 files associated with each year: e.g.
> comp198601, comp198602, ... comp198612 through to comp199501,
> comp199502 ... comp199512.
> I am trying to automate the reading in of these files, but am
> struggling to find an adequate way of achieving this. The closest
> I've got is by doing:
> year <- 1986:1995
> month <- sprintf("%02d", 1:12) # formats numbers to 2 digits (for
> maintaining leading zeros in file names)
> filelist <- paste("C:\\Documents and Settings\\Data\
> \comp",year,month,".asc", sep="")
>  "C:\\Documents and Settings\\Data\\comp198601.asc"
>  "C:\\Documents and Settings\\Data\\comp198702.asc"
>  "C:\\Documents and Settings\\Data\\comp198803.asc"
>  "C:\\Documents and Settings\\Data\\comp198904.asc"
>  "C:\\Documents and Settings\\Data\\comp199005.asc"
>  "C:\\Documents and Settings\\Data\\comp199106.asc"
>  "C:\\Documents and Settings\\Data\\comp199207.asc"
>  "C:\\Documents and Settings\\Data\\comp199308.asc"
>  "C:\\Documents and Settings\\Data\\comp199409.asc"
>  "C:\\Documents and Settings\\Data\\comp199510.asc"
>  "C:\\Documents and Settings\\Data\\comp198611.asc"
>  "C:\\Documents and Settings\\Data\\comp198712.asc"
> I need 1986 to remain fixed whilst it cycles through 01 to 12,
> before it moves onto 1987 and cycles again. There should be 120
> outputs in total (10 years each with 12 months), but at present it's
> only reaching 12 outputs.
> I'd be grateful to learn what I'm doing wrong here so that I can
> solve this.
> Many thanks as ever,
> 25GB of FREE Online Storage – Find out more
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
School of Physics
University of Exeter
EX4 4QL, UK
Phone: +44 1392 264187
More information about the R-help