[R] sum of certain length

Bill.Venables at csiro.au Bill.Venables at csiro.au
Mon May 24 02:32:14 CEST 2010


This is one way to do it.  Suppose your data is in the file "rainfall.txt", as set out below.  Then

> dat <- read.table("rainfall.txt", header = TRUE)
> dat <- within(dat, {
+   date <- as.Date(paste(year, month, day, sep="-"))
+   week <- factor(as.numeric(date - date[1]) %/% 7)
+ })
> wRain <- with(dat, tapply(rain, week, sum))
> wRain
   0    1    2    3    4    5 
 0.0 27.6  0.8  0.0  0.0  0.0 
> 

 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Roslina Zakaria
Sent: Monday, 24 May 2010 10:09 AM
To: r-help at r-project.org
Subject: [R] sum of certain length

Hi r-users,
 
I have this data below.  I would like to obtain the weekly rainfall sum.  That is I would like to find sum for day 1 to day 7, day 8 - day15, and so on.
   year month day rain
1  1922     1   1  0.0
2  1922     1   2  0.0
3  1922     1   3  0.0
4  1922     1   4  0.0
5  1922     1   5  0.0
6  1922     1   6  0.0
7  1922     1   7  0.0
8  1922     1   8  6.6
9  1922     1   9  1.5
10 1922     1  10  0.0
11 1922     1  11  0.0
12 1922     1  12  4.8
13 1922     1  13 14.7
14 1922     1  14  0.0
15 1922     1  15  0.0
16 1922     1  16  0.0
17 1922     1  17  0.0
18 1922     1  18  0.0
19 1922     1  19  0.0
20 1922     1  20  0.8
21 1922     1  21  0.0
22 1922     1  22  0.0
23 1922     1  23  0.0
24 1922     1  24  0.0
25 1922     1  25  0.0
26 1922     1  26  0.0
27 1922     1  27  0.0
28 1922     1  28  0.0
29 1922     1  29  0.0
30 1922     1  30  0.0
31 1922     1  31  0.0
32 1922     2   1  0.0
33 1922     2   2  0.0
34 1922     2   3  0.0
35 1922     2   4  0.0
36 1922     2   5  0.0
37 1922     2   6  0.0
38 1922     2   7  0.0
39 1922     2   8  0.0
40 1922     2   9  0.0

Thank you.


      
	[[alternative HTML version deleted]]



More information about the R-help mailing list