[R] Sum of two consecutive number in dataset.

William Dunlap wdunlap at tibco.com
Wed Oct 15 17:11:00 CEST 2014


Break down your problem into parts:
# compute two-day totals.  I use filter here, but there are many ways
twoDayTotal <- function (x, init = 0)
{
    # init lets you supply rainfall from day previous to first in x
    filter(c(init, x), c(1, 1))[-length(x)]
}
# compute the first time a logical vector contains a TRUE
firstTime <-function (x, time. = as.vector(time(x)))
{
    stopifnot(is.logical(x))
    time.[!is.na(x) & x][1]
}
# combine them
f <- function(x, ...) firstTime(x>22 | twoDayTotal(x)>22, ...)
# test it
f(c(5, 20, 3, 4, 25))
# [1] 2
f(c(0, 25, 3, 4, 25), time=92:96)
# [1] 93
f(ts(c(0, 25, 3, 4, 25), start=92))
# [1] 93


Bill Dunlap
TIBCO Software
wdunlap tibco.com


On Wed, Oct 15, 2014 at 12:01 AM, Frederic Ntirenganya
<ntfredo at gmail.com> wrote:
> Dear All,
>
> i am solving the following problem in my work.
>
> The first day from April 01 that gets more than 20 mm on a single day, or
> totalled
> over 2 consecutive days. i.e April 01 = 92th day of the year.
>
> The column of interest is "Rain".
>> head(Samaru56)
>   Year Day Rain
> 1 1928   1    0
> 2 1928   2    0
> 3 1928   3    0
> 4 1928   4    0
> 5 1928   5    0
> 6 1928   6    0
>
> I used the loop below but it is not printing anything.
>
> sow_day=c()
> for (i in 1928:1983){
>   for (j in 92:366){
>     k=j-1
>     s_rain=Samaru56$Rain[k] + Samaru56$Rain[j]
>     if (s_rain>=20)
>       sow_day=j
>       break
>   }
>   Samaru56$year=Samaru56$Year[sow_day]
>   Samaru56$Day=Samaru56$Day[sow_day]
>   Samaru56$Rain=Samaru56$Rain[sow_day]
> }
> sow_day
>
> Any idea is welcome on how I can solve this problem. Thanks
>
> --
> Frederic Ntirenganya
> Maseno University,
> Kenya.
> Mobile:(+254)718492836
> Email: fredo at aims.ac.za
> https://sites.google.com/a/aims.ac.za/fredo/
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list