Chayan Lahiri
Chayan Lahiri

Reputation: 109

Outputting column means for arbitrary number of columns

I have attached a screen shot of my data file. Each column represents daily data collected by a probe at half hour intervals. I want to output in a CSV file the daily averages for each probe. So far I have the following code

sink('d2.csv')
x<-1
y<-48
for(i in 1:123) {
    W=E.2.[x:y]
    M=mean(W)
    print(M)
    x<-x+48
    y<-y+48
}
sink()

which averages each column separately and writes it to a CSV file. What I want to do is to have a code that could work on all the columns and write it to a CSV file.

    TIMESTAMP       E.2.    E.3.    E.4.    E.5.    E.6.    E.7.    E.8.    E.9.    E.10.   E.11.   E.12.   E.13.
1   3/16/2013 0:00  108.1   166.4   238.41  261.2   373.5   324.27  278.94  514.2   629.8   607.9   334.9   323.59
2   3/16/2013 0:30  109.5   165.6   237.4   261.19  367.1   324.2   278.53  513.2   631.8   609.3   335.0   323.19
3   3/16/2013 1:00  110.6   165.5   236.48  261.17  368.1   324.2   278.13  512.4   631.2   609.3   335.0   323.56
4   3/16/2013 1:30  111.4   165.6   235.69  261.13  375.1   324.2   277.49  511.6   629.1   606.6   335.2   323.5
5   3/16/2013 2:00  112.2   165.7   234.88  261.09  379.6   324.21  276.85  510.6   629.5   607.3   335.3   323.67
6   3/16/2013 2:30  112.3   166.2   234.3   261.09  378.2   324.21  276.38  509.9   630.7   607.6   335.6   323.88

Upvotes: 0

Views: 56

Answers (1)

John Coleman
John Coleman

Reputation: 51998

It is hard to know for sure without knowing more about the structure of your data and exactly what you are trying to do, but by using the rollapply function, everything that you need can probably be put in two lines of code (assuming that df is the name of your dataframe):

library(zoo)
write.csv(rollapply(df[,-1],48,mean,by = 4),"d2.csv")

On Edit: I used by = 4 because your code had lines like x <- x + 4. You seem to want to increment by 48. It isn't really a sliding mean any more in the sense that successive windows are now disjoint, though this approach still works:

write.csv(rollapply(df[,-1],48,mean,by = 48),"d2.csv")

will give you 123 rows per column.

Upvotes: 1

Related Questions