Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Make data easily reproducible
- df <- data.frame(day=c(24, 21, 20, 10, 20, 20, 10, 15),
- month = c("Jun", "Mar", "Jan", "Dec", "Jun", "Jan", "Dec", "Dec"))
- ## Convert each month-day combo to its corresponding "julian date"
- datestring <- paste("1963", match(df[[2]], month.abb), df[[1]], sep = "-")
- date <- strptime(datestring, format = "%Y-%m-%d")
- julian <- as.integer(strftime(date, format = "%j"))
- ## Transitions between years occur wherever julian date increases between
- ## two observations
- df$year <- 1963 - cumsum(diff(c(julian[2], julian))>0)
- df$year <- 1963 + cumsum(c(0L, diff(100L*as.integer(
- factor(df$month, levels = month.abb)) + df$day) < 0))
- df
- day month year
- 1 24 Jun 1963
- 2 21 Mar 1964
- 3 20 Jan 1965
- 4 10 Dec 1965
- 5 20 Jun 1966
- 6 20 Jan 1967
- 7 10 Dec 1967
- 8 15 Dec 1967
Add Comment
Please, Sign In to add comment