'Separate day of year into month and day of month columns in R
For simplicity, I have data that has two columns. One column is the year (year) and the other is the number of days (yday). So year with a value of 1980 and yday with a value of 1 is January 1, 1980. Year with a value of 1980 and yday with a value of 365 is December 31, 1980. How do I separate the single yday column into two columns; a month column and the day of the month column? For example, 365 would be 12 for the month and 31 for the day. Thanks in advance.
Solution 1:[1]
Create a Date from the yday + year columns, then extract the day of month, and month separately:
dat <- data.frame(year=1980, yday=c(1,365))
# year yday
#1 1980 1
#2 1980 365
dat[c("month","day")] <- lapply(c("%m","%d"), \(x) {
d <- as.Date(paste(dat$year, dat$yday), format="%Y %j")
as.integer(format(d, x))
})
# year yday month day
#1 1980 1 1 1
#2 1980 365 12 30
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thelatemail |
