[R] If-then with Dates in Date Ranges
MacQueen, Don
macqueen1 at llnl.gov
Wed Sep 18 21:43:27 CEST 2013
On possible way, if I understand the question correctly, is to use the
findInterval() function.
Otherwise, solutions depend on details you haven't included.
Here's an example from ?findInterval
x <- 2:18
v <- c(5, 10, 15) # create two bins [5,10) and [10,15)
cbind(x, findInterval(x, v))
The cut() function might also work.
Based on the example from ?findInterval, try this:
> bnds <- Sys.Date() + seq(0,15,5)
> vals <- Sys.Date() + 1:15
> cbind(vals, findInterval(vals,bnds))
vals
[1,] 15967 1
[2,] 15968 1
[3,] 15969 1
[4,] 15970 1
[5,] 15971 2
[6,] 15972 2
[7,] 15973 2
[8,] 15974 2
[9,] 15975 2
[10,] 15976 3
[11,] 15977 3
[12,] 15978 3
[13,] 15979 3
[14,] 15980 3
[15,] 15981 4
> tmp <- findInterval(vals,bnds)
> cbind(format(vals),tmp) tmp
[1,] "2013-09-19" "1"
[2,] "2013-09-20" "1"
[3,] "2013-09-21" "1"
[4,] "2013-09-22" "1"
[5,] "2013-09-23" "2"
[6,] "2013-09-24" "2"
[7,] "2013-09-25" "2"
[8,] "2013-09-26" "2"
[9,] "2013-09-27" "2"
[10,] "2013-09-28" "3"
[11,] "2013-09-29" "3"
[12,] "2013-09-30" "3"
[13,] "2013-10-01" "3"
[14,] "2013-10-02" "3"
[15,] "2013-10-03" "4"
For your one-line fragment, the basic syntax would be
if (StartDate >= Beg1Date & EndDate <= Beg1Date) inperiod <- 1 else
inperiod <- 0
but of course that handles only one time interval (bin).
A huge if, else if, else if, ... thing could be used, but R has a better
way!
-Don
--
Don MacQueen
Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062
On 9/17/13 10:52 AM, "Zd Gibbs" <zd.gibbs at yahoo.com> wrote:
>Hello everyone.
>
>I am very much a beginner with R and I am trying to turn the following
>if-then statement into R code. More detail. I want to create a new
>variable: "inperiod" that will be a numeric code. So if a specific event
>start date (StartDate) is greater or equal to a testing date (Beg1Date)
>AND the event end date (EndDate) is less than or equal to the testing
>date (Beg1Date), I want the inperiod code to be 1. I will do this for a
>range of dates so that the code can be anywhere from 1-25.
>
>If StartDate >= Beg1Date & EndDate <= Beg1Date inperiod = 1.
>
>Thanks for any help.
>
>Zeda
> [[alternative HTML version deleted]]
>
More information about the R-help
mailing list