0

I know how to get the week from an index, but don't know the other way around: how to create an index if I have the calendar weeks (in this case, from an SAP system with 0CALWEEK as 201501, 201502 ... 201552, 201553.

Found this: How to Parse Year + Week Number in R? but the day is needed and it's not clear how to set it, especially at the end of the year (Year - week - day: YEAR-53-01 does not always exist, since the first day of week 53 might be Monday, then 01 (Sunday) is not in that week.

I could try to get in the source system the first day of the corresponding week (through SQL) but thought R might do it easier...

Do you have any suggestions?

(Which first day of the week would be not important , since I will create all objects the same way and then merge/cbind them, then continue the analysis. If zoo is easier, I'll go with it)

Thanks!

4554888
  • 87
  • 1
  • 11

3 Answers3

1

The problem is that all indices end in 2015-07-29:

data <- 1:4
weeks <- c('201501','201502','201552','201553')
weeks_2 <- as.Date(weeks,format='%Y%w') 
xts(data, order.by = weeks_2)

[,1]

2015-07-29 1

2015-07-29 2

2015-07-29 3

2015-07-29 4

test <- xts(data, order.by = weeks_2)
index(test)

[1] "2015-07-29" "2015-07-29" "2015-07-29" "2015-07-29"

4554888
  • 87
  • 1
  • 11
0

You can use as.Date() function, I think is the easiest way:

weeks <- c('201501','201502','201552','201553')
as.Date(paste0(weeks,'1'),format='%Y%W%w') # paste a dummy day
## [1] "2015-01-05" "2015-01-12" "2015-12-28" NA   

Where:

%W: Week 00-53 with Monday as first day of the week

or

%U: Week 01-53 with Sunday as first day of the week

%w: Weekday 0-6 Sunday is 0

For this year, week number 53 doesn't exist. And If you want to start with 2015-01-01, just set the right week day:

weeks <- c('201500','201501','201502','201551','201552')
as.Date(paste0(weeks,'4'),format='%Y%W%w')
## [1] "2015-01-01" "2015-01-08" "2015-01-15" "2015-12-24" "2015-12-31"
aldo_tapia
  • 1,153
  • 16
  • 27
0

You may try with substr() and lubridate

library(lubridate)
# a number from your list: 201502
# set the year
x <- ymd("2015-01-1")
# retrieve second week
week(x) <- 2
x
[1] "2015-01-08" 

you can use the result for your Index or rownames().

zoo and xts are great for time series once you have set the names, be sure to remove any column with dates from your data frame

Elio Diaz
  • 566
  • 2
  • 19