Gagan Thind
Gagan Thind

Reputation: 11

A function that changes a given date to the same day and month in another year

I have a function called change_year in which two arguments are accepted being a date type value and year as a number.

I must convert the date type in to a string then extract the month and day from that. From there I need to create a string representing the date in a new year.

For example, "2020-01-01" becomes "2021-01-01" and so forth. How do I write this in an effective manner in R?

Upvotes: 1

Views: 43

Answers (2)

Onyambu
Onyambu

Reputation: 79298

You could do:

change_year <- function(input, year = NULL){
  a <- as.POSIXlt(input)
  if(!is.null(year)) a$year <- year - 1900
  a
}

change_year("2012-10-23", 2020)
[1] "2020-10-23 PDT"

Upvotes: 0

M--
M--

Reputation: 29119

change_year <- function(inpDate, outYear = NULL) {

  outDate = inpDate

  if (!is.null(outYear)){

  require(lubridate)

  if(class(inpDate) == "character"){inpDate = ymd(inpDate)}

  inpMonth = month(inpDate)
  inpDay = day(inpDate)

  outDate = ymd(paste(outYear, inpMonth, inpDay, sep = "-"))
  }
  return(outDate)   
}
test.1 <- change_year("2012-10-23", "2020")
test.1
#> [1] "2020-10-23"
class(test.1)
#> [1] "Date"

test.2 <- change_year("2012-10-23")
test.2
#> [1] "2012-10-23"

Upvotes: 2

Related Questions