I have approximately 300 csv files of wind speed, temp, pressure, etc, columns and each row is a different time from 2007 to 2012. Each file is from a different location. I want to combine all files into one that is the average of all 300 files. So the new file would have the same number of rows and columns of each individual file but each cell would be a corresponding average of all the 300 files. Is there an easy way to do this?
Asked
Active
Viewed 1,208 times
3
-
possible duplicate of [Importing multiple .csv files into R](http://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r) – Metrics Apr 22 '15 at 16:14
-
1@Metrics the linked post doesn't solve the problem because it doesn't address how to average all the csvs after they've been read into a list. – josliber Apr 22 '15 at 16:41
1 Answers
6
Following this post, you could read all the files into a list (here I've assumed they're named weather*.csv):
csvs <- lapply(list.files(pattern="weather*.csv"), read.csv)
All that remains is to take the average of all those data frames. You might try something like:
Reduce("+", csvs) / length(csvs)
If you wanted to only add a subset of the columns, you could pass Reduce
a list of data frames with the appropriate subset of the columns. For instance, if you wanted to remove the first column from each, you could do something like:
Reduce("+", lapply(csvs, "[", -1)) / length(csvs)
-
Thad did it Josilber. I was a little surprised there wasn't something more automatic but this solution Is nice. Thanks for your help! – user3687879 Apr 22 '15 at 20:24