Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of values within a week

I want to sum the values in each column of a frame by week. I can do the mean, but the sum doesn't work for some reason:

> zoo.data <- zoo(data.frame(x=11:20,y=1:10),as.Date(1:10,origin="1970-01-01"))
> apply.weekly(zoo.data, mean)
            x y
1970-01-04 12 2
1970-01-11 17 7
> apply.weekly(zoo.data, sum)
1970-01-04 1970-01-11 
        42        168 

What's going on?

like image 297
Xodarap Avatar asked Dec 09 '12 22:12

Xodarap


People also ask

How do I sum last 7 days in Excel?

The daily hours column(B) is formatted for # and the formula for the Total for last 7days(column C) is =SUMIFS(B:B,A:A,">="&TODAY()-7,B:B,"<="&TODAY()).

How do I sum hours worked in a week in Excel?

Write each day of the week in its own row, then create a new cell label titled "TOTAL." The cells next to this one will display the total number of hours worked and pay received for the week. This is applied using the function "=SUM(E2:E8)" to calculate total hours.


1 Answers

This is a result of the fact that the xts authors have decided to add a mean.xts method to mimic the old behavior of base R (and which is essentially colMeans). mean.xts is now dispatched on xts objects instead of mean.default, and apply.weekly temporarily converts your zoo object to an xts internally.

R> apply.weekly(zoo.data, mean)
            x y
1970-01-04 12 2
1970-01-11 17 7
R> apply.weekly(zoo.data, mean.default)
1970-01-04 1970-01-11 
         7         12 

But, I think this is what you want to do:

R> apply.weekly(zoo.data, colMeans)
            x y
1970-01-04 12 2
1970-01-11 17 7
R> apply.weekly(zoo.data, colSums)
             x  y
1970-01-04  36  6
1970-01-11 119 49
like image 73
GSee Avatar answered Oct 20 '22 01:10

GSee