[R] How to save the output of "split" command as series of .csv files

Peter Ehlers ehlers at ucalgary.ca
Mon Jan 10 22:57:09 CET 2011


On 2011-01-10 12:56, menno wrote:
>
> Hello,
>
> I am looking for a way to quickly split a data frame containing daily
> temperature readings into a series of individual data frames, one for each
> year, in order to save them as individual .csv files which will be named
> according to Year. I would prefer not to use a series of "subset" commands
> given that there are a differing number of years for the various location.
>
> The data looks like this:
>
>     Day Month   Community     Year     MaxTemp MinTemp
>     	1     1  	      '241552' 	        	1990      44        	 29
>     	2     1  	      '241552' 		        1990      39         	 20
>     	3     1        	'241552' 		        1990      35     	      24
> 	.	.	.			.		.	.	
> 	.	.	.			.		.	.
>     	4     1  	     '241552' 	         	1991      23         	 23
>     	5     1  	     '241552' 		        1991      33     	         31
>     	6     1  	     '241552' 		        1991      45          	 44
> 	.	.	.			.		.	.	
> 	.	.	.			.		.	.
>
>
> The "split" command   (data2<-split(data, data$Year)) essentially does what
> I want, but I am unable to take the output from this command and save the
> data from individual years in separate files. I would ideally like to have a
> series of output files named "241552_1990", "241552_1991", etc. These data
> files will then be run through a loop that I have already created. I have
> attempted to feed the output of the split command directly into my
> pre-existing loop, but doing so will require major re-writes to my script
> due to column/row naming issues.
>
>
> Any information anyone could provide would be greatly appreciated.
>
> Thanks for your time,
>
> David Roth
>

How about a simple loop:

  for(n in names(data2))
       write.table(data2[[n]],
         file = paste(dat2[[n]][, "Community"][1],
                      "_", n, ".TXT", sep=""))


Peter Ehlers

>
>



More information about the R-help mailing list