GabyLP
GabyLP

Reputation: 3781

r - I need to transform a number to a date

I need to add a calendar date depending on the number stored in a field .

final_muestra1<-data.frame(prior_day1=c(1:17) )

I tried the following function:

gg<-function(d) {
  august <- (d < 8)
  d[august] <- as.Date("2014-08-01") + (d[august]-1)
  d[!august] <- as.Date("2014-07-01") + (d[!august]-1)
  return(d) 
}



final_muestra1$xx<-gg(final_muestra1$prior_day1)

But I get:

  prior_day1    xx
1           1 16283
2           2 16284
3           3 16285
4           4 16286
5           5 16287
6           6 16288
7           7 16289
8           8 16259
9           9 16260

When I need to get:

 prior_day1    xx
    1           1 2014-08-01
    2           2 2014-08-02
    3           3 2014-08-03

.....
    7           7 2014-07-07
    8           8 2014-07-08

Thanks!

Upvotes: 0

Views: 51

Answers (1)

Mike.Gahan
Mike.Gahan

Reputation: 4615

You might need to re-define d as a Date object before returning it. You are only defining part of the d vector as a Date object at a time.

gg<-function(d) {
  august <- (d < 8)
  d[august] <- as.Date("2014-08-01") + (d[august]-1)
  d[!august] <- as.Date("2014-07-01") + (d[!august]-1)
  d <- as.Date(as.numeric(d),format="%Y-%m-%d",origin=as.Date("1970-01-01"))
  return(d) 
}

Upvotes: 1

Related Questions