Reputation: 911
I've created a large list of elements separated by year like so:
1961: 'data.frame': 365 obs of 4 variables:
..$ Year: int [1:365]
..$ Rainfall: int [1:365]
..$ PET: int [1:365]
..$ MeanT: int [1:365]
1962: 'data.frame': 365 obs of 4 variables:
..$ Year: int [1:365]
..$ Rainfall: int [1:365]
..$ PET: int [1:365]
..$ MeanT: int [1:365]
...all the way up to 2007. I want to create separate text files for each year to be used in another program, containing the four columns of data without the column headers.
It would be simple to do this in excel but I have a lot of data to process and would like to be able to use R to automate the process and save a good deal of time.
Upvotes: 0
Views: 98
Reputation: 51
After having chatted with Pad, on reddit, we found a solution, it is based on akrun's and Pierre's comments from above:
lapply(names(lst),function(x) write.table(cbind(c(1:dim(lst[[x]])[1]), lst[[x]][-1]), file = paste0('',x,'.txt'), quote = F, row.names = F, col.names = F, sep = ","))
In addition to writing the file, the code also removes the first column, substituting it with the numbers from 1-365 (or 1 to the number of rows in the provided data.frame).
Upvotes: 2
Reputation: 3786
I know that it's R heresy, but even though it may run slower, a for loop will make it easy to get the file name from the list item name:
for(i in 1:length(mylist)){
filename <- paste0(names(mylist)[i],".csv")
write.table(mylist[[i]], file=filename, row.names = FALSE, col.names = FALSE, sep=",")
}
Upvotes: 1