Thomas Barningham
2014-Jun-17 12:00 UTC
[R] Writing "monthly" .txt or .csv files from a long time series
Dear R users, I have a .txt file of time series data from the middle of 1999 through to the end of 2012. There are two columns in the file, the first is a decimal date, the second is an atmospheric tracer value and looks like this: Date APO 1999.47945560 -168.48 1999.47948410 -158.08 1999.47951270 -163.79 1999.47956990 -164.38 1999.47959850 -173.94 1999.47962700 -161.92 1999.47965560 -154.36 1999.47968420 -147.55 1999.47971280 -157.06 1999.47974140 -151.21 1999.47976990 -141.63 1999.47979850 -147.97 What I'd now like to do is write new .txt (or .csv) files based on the month of the year so that I have separate text files for Jan, Feb, Mar etc for each year 1999, 2000, 2001 etc. using either the write.table or write.csv function. Is there an easy way to do this in R? Google key word searches have not been fruitful and the only other way I can see to do this is "manually" in excel, which would take a long time. I'm hoping there's a neat bit of code to do this. Many thanks Thomas -- Thomas Barningham Centre for Ocean and Atmospheric Sciences School of Environmental Sciences University of East Anglia Norwich Research Park Norwich NR4 7TJ
David Winsemius
2014-Jun-17 20:35 UTC
[R] Writing "monthly" .txt or .csv files from a long time series
On Jun 17, 2014, at 5:00 AM, Thomas Barningham wrote:> Dear R users, > > I have a .txt file of time series data from the middle of 1999 through > to the end of 2012. There are two columns in the file, the first is a > decimal date, the second is an atmospheric tracer value and looks like > this: > > Date APO > 1999.47945560 -168.48 > 1999.47948410 -158.08 > 1999.47951270 -163.79 > 1999.47956990 -164.38 > 1999.47959850 -173.94 > 1999.47962700 -161.92 > 1999.47965560 -154.36 > 1999.47968420 -147.55 > 1999.47971280 -157.06 > 1999.47974140 -151.21 > 1999.47976990 -141.63 > 1999.47979850 -147.97 > > What I'd now like to do is write new .txt (or .csv) files based on the > month of the year so that I have separate text files for Jan, Feb, Mar > etc for each year 1999, 2000, 2001 etc. using either the write.table > or write.csv function. Is there an easy way to do this in R?There is a breaks argument to cut.POSIXt function that will accept "month" as an argument. With a suitable offset that 'Date' column looks like it would be suitable for `as.Date.numeric`. Try something along these lines: dat$dt <- as.Date(dat$Date) dat$mon <- cut(dat$dt, breaks="month") lapply( split(dat, dat$mon), function(dts) write.csv( dts, file=as.character(dts$mon[1]) ))> > Google key word searches have not been fruitful and the only other way > I can see to do this is "manually" in excel, which would take a long > time. I'm hoping there's a neat bit of code to do this.The above seemed acceptably "neat" to me, although it remains only modestly tested. -- David Winsemius Alameda, CA, USA