[R] find date between two other dates
Rui Barradas
ruipbarradas at sapo.pt
Sun Aug 5 23:49:56 CEST 2012
Hello,
You can use a function that returns the number you want, not a logical
value.
But first, it's a bad idea to have a data.frame and a vector with the
same name, so, in what follows, I've altered the df name.
ddate <- c("29/12/1998 20:00:33", "02/01/1999 05:20:44", "02/01/1999
06:18:36", "02/02/1999 07:06:59", "02/03/1999 07:10:56", "02/03/1999
07:57:18")
ddate <- as.POSIXct(strptime(ddate, "%d/%m/%Y %H:%M:%S"), "GMT")
ddat <- data.frame(ddate=ddate) # Here, different name.
season.month <- function(x){
x <- as.integer(format(x, format="%m"))
ifelse(x == 12L, 1L, x + 1L)
}
season.month(ddate)
ddat$season <- season.month(ddate)
str(ddat)
'data.frame': 6 obs. of 2 variables:
$ ddate : POSIXct, format: "1998-12-29 20:00:33" "1999-01-02 05:20:44" ...
$ season: int 1 2 2 3 4 4
ddat
ddate season
1 1998-12-29 20:00:33 1
2 1999-01-02 05:20:44 2
3 1999-01-02 06:18:36 2
4 1999-02-02 07:06:59 3
5 1999-03-02 07:10:56 4
6 1999-03-02 07:57:18 4
Hope this helps,
Rui Barradas
Em 05-08-2012 21:30, penguins escreveu:
> Hi,
>
> I am trying to assign "Season" values to dates depending on when they occur.
>
> For example, the following dates would be assigned the following "Season"
> numbers based on the "season" intervals detailed below in the code:
>
> ddate Season
> 29/12/1998 20:00:33 1
> 02/01/1999 05:20:44 2
> 02/01/1999 06:18:36 2
> 02/02/1999 07:06:59 3
> 02/03/1999 07:10:56 4
> 02/03/1999 07:57:18 4
>
> My approach so far doesnt work because of the time stamps and is probably
> very long winded. However, to prevent errors I would prefer to keep the date
> formats as dd/mm/yyyy as oppose to a numeric format. Any help on the
> following code would be gratefully recieved:
>
> ddate <- c("29/12/1998 20:00:33", "02/01/1999 05:20:44", "02/01/1999
> 06:18:36", "02/02/1999 07:06:59", "02/03/1999 07:10:56", "02/03/1999
> 07:57:18")
> ddate <- as.POSIXct(strptime(ddate, "%d/%m/%Y %H:%M:%S"), "GMT")
>
> is.between<-function(x, a, b) {
> (x > a) & (b > x)
> }
>
> ddate$s1 <- is.between(ddate, 01/12/1998 00:00:00, 31/12/1998 23:59:59)
> ddate$s2 <- is.between(ddate, 01/01/1999 00:00:00, 31/01/1999 23:59:59)
> ddate$s3 <- is.between(ddate, 01/02/1999 00:00:00, 28/02/1999 23:59:59)
> ddate$s4 <- is.between(ddate, 01/03/1999 00:00:00, 31/03/1999 23:59:59)
>
> Many thanks
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/find-date-between-two-other-dates-tp4639231.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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