2

my x is 10th week of 2015 and y is 20th week of 2015.

x<-as.Date("201510", "%Y%U")
y<-as.Date("201520", "%Y%U")

I want to get difference between x-y in number of weeks. So x-y should be -10. When I try with following codes, I get 0 or 0s.

interval(x, y) / weeks(1)

this gives me 0

as.period(x- y, unit = "weeks")

this gives me 0s.

What am I missing here?

Louis
  • 55
  • 5
  • these post might be of help: [Transform year/week to date object](https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object) and [How to Parse Year + Week Number in R?](https://stackoverflow.com/questions/9380435/how-to-parse-year-week-number-in-r) – phiver Oct 25 '18 at 16:55
  • thanks. I've actually seen those posts before writing this post. They don't really go over calculating interval of the dates... – Louis Oct 25 '18 at 17:13

2 Answers2

2

You don't need lubridate for this. Here is a base R option:

## you need to define a week day to be able to compute the time interval
x <- as.Date("2015107", "%Y%U%u") # by appending 7 (and %u) to the string, we are taking the last day of the week (i.e. sunday)
y <- as.Date("2015207", "%Y%U%u")
## time interval
difftime(x, y, units = "weeks") 
# Time difference of -10 weeks
as.numeric(difftime(x, y, units = "weeks"))
# [1] -10
nghauran
  • 6,648
  • 2
  • 20
  • 29
  • Thanks! I am try to expend this to a variable in dataframe. when I try x <- as.Date(df$var1, "%Y%U%u") I get an error. why would this be? df$var1 is basically bunch of values like "2015107" – Louis Oct 25 '18 at 19:36
1

If you do want a lubridate solution, use dweeks instead of weeks.

x<-as.Date("2015107", "%Y%U%u") # using @ANG's edit to make the dates distinct
y<-as.Date("2015207", "%Y%U%u")

library(lubridate)
interval(y, x) / dweeks(1)
[1] -10
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
  • Thanks! I am try to expend this to a variable in dataframe. When I try x <- as.Date(df$var1, "%Y%U%u") I get an error. why would this be? df$var1 is basically bunch of values like "2015107" – Louis Oct 25 '18 at 19:37
  • For people to answer you knowledgeably, you'll have to share how that data is stored in R, for instance by adding the output of `dput(head(df$var1))` to the body of your original question. That will show not only what the data looks like, but in what form it's saved in R, making your question reproducible. – Jon Spring Oct 25 '18 at 19:46