[R] Working with Date

Jim Lemon jim at bitwrit.com.au
Tue Dec 31 23:57:08 CET 2013


On 01/01/2014 08:53 AM, Christofer Bogaso wrote:
> Hi again,
>
> Happy new year 2014 to every R gurus and users.
>
> I am struggling with some calculation with dates... Let say I have
> following vector of months:
>
> Months<- c("Jan", "Dec", "Mar")
>
> Now I need to assign year with them. This assignment will be based on some
> given date. Let say my given date is :
>
> Given_Date<- as.Date("2013-12-23")
>
> So in this case, the modified month will be:
>
>   Months_Mod<- c("Jan-2014", "Dec-2013", "Mar-2014")
>
> However if given date is:
>
> Given_Date<- as.Date("2014-01-04")
>
> then the modified months will be:
>
>   Months_Mod<- c("Jan-2014", "Dec-2014", "Mar-2014")
>
> My problem is that, I can not extablish some logic around it, so that I can
> do it programmatically for any Month-vector and for any Given-date.
>
> Can someone help me to accomplice this?
>
Hi Christofer,
I would like to be an accomplice in this, but I can't quite work out 
your logic. I thought that you might want:

IF Given_Date is in the same month as an element of Months

THEN use the year in Given_Date

ELSE use the year in Given_Date plus 1

However, when I programmed it:

assignYear<-function(index_date,months) {
  index_year<-as.numeric(format(index_date,"%Y"))
  index_month<-which(months==format(index_date,"%b"))
  dates<-as.Date(paste(index_year+1,months,"1",sep="-"),"%Y-%b-%d")
  dates[index_month]<-
   as.Date(paste(index_year,months[index_month],"1",sep="-"),"%Y-%b-%d")
  return(format(dates,"%Y-%b"))
}

it didn't work for the second example. Could you give some idea of what 
you want to do?

Jim




More information about the R-help mailing list