Reputation: 3133
I'm trying to get biweekly/fortnightly numbers for dates.
the weeks can be done like(from documentation):
data <- read.csv("dummy data.csv")
data$Date <- as.Date(data$Date, "%d-%m-%y")
data$weeks <- format(data$Date, "%U-%Y")
this gives:
> data
Date weeks
2017-01-07 01-2017
2017-01-08 02-2017
2017-01-15 03-2017
I want to calculate biweeks/fortnights from data like i did above.
expected output:
Date weeks fortnights
2017-01-07 01-2017 01-2017
2017-01-08 02-2017 01-2017
2017-01-15 03-2017 02-2017
How do I do this for a dataframe?
Upvotes: 1
Views: 1231
Reputation: 389275
How about to get the fortnight, we extract the month which are already passed, multiply it with 2 and add 1 or 2 based on date. So here any date after 14 is considered as next fortnight.
(as.integer(format(df$Date, "%m")) - 1) * 2 +
(as.integer(format(df$Date, "%d")) > 14) + 1
#[1] 1 1 2
If you also want the year we can do
paste0((as.integer(format(df$Date, "%m")) - 1) * 2 +
(as.integer(format(df$Date, "%d")) > 14) + 1, format(df$Date, "-%Y"))
#[1] "1-2017" "1-2017" "2-2017"
data
df <- structure(list(Date = structure(c(17173, 17174, 17181), class = "Date"),
weeks = structure(1:3, .Label = c("01-2017", "02-2017", "03-2017"
), class = "factor")), row.names = c(NA, -3L), class = "data.frame")
Upvotes: 1
Reputation: 129
You can use the "week" function from the "lubridate" package. e.g.
lubridate::week(as.Date("2017-06-08"))
will return 23.
lubridate::week(as.Date("2017-01-07"))
will return 1.
lubridate::week(as.Date("2017-01-08"))
will return 2.
To return the fortnights it will be just a matter of dividing each of the above with the number 2 and "ceil" the result e.g.
ceiling(lubridate::week(as.Date("2017-06-08")) / 2)
For information on the ceiling()
function please see the documentation, i.e.
?ceiling
.
P.S. I think in this case it is safer to use the ceiling()
function instead of the round()
function, although as long as your arguments are positive, the behaviour will be similar for both.
Upvotes: 3