0

I have the problem that I would like to change a date column that currently has the class"character" to a the class "date". The format here is yyyyww.

You can see a snippet of the dataframe here:

Avsales <- c("4500", "6000", "5500", "5000", "5100")
Week <- c("2003-23", "2003-24", "2003-25", "2003-26", "2003-27")
Data <- data.frame(Avsales, Week)

I know there are already similar questions here on the topic (such as Transform year/week to date object) and I already tried to apply the solution, however I would like to keep the weeks and not make them single days, since it is an average of the sales for the whole week.

For this reason I tried the following solution:

data$week <- as.Dates(data$Week, yyyyww = TRUE)

However, the class remains "character" and not "date".

For that reason I tried several other options with as.Date like

data$week <- as.Date(data$Week, format = "%Y-%W")

But as I want to have the format "yyyy-ww" it didn't work for me.

Could it be because date always means the specific day and I need a completely different approach for this?

I would be happy if you can help me in this regard. Thanks!

3 Answers3

1

You cannot store week as Date because Date has to be a day number. However you can store week number as week with 'aweek' package. See the code and output if it helps.

Avsales <- c("4500", "6000", "5500", "5000", "5100")
Week <- c("2003-23", "2003-24", "2003-25", "2003-26", "2003-27")
Data <- data.frame(Avsales, Week)

library(aweek)

Data$Week = as.aweek(as.Date(paste(Data$Week, 1, sep="-"), "%Y-%U-%u"),2)
Data

# Avsales       Week
# 1    4500 2003-W23-7
# 2    6000 2003-W24-7
# 3    5500 2003-W25-7
# 4    5000 2003-W26-7
# 5    5100 2003-W27-7
0

to convert what you have you can use

as.Date("2003-23", format = "%Y-%V")

to which the output will be

"2003-05-01"

More generally Date in R is defined as "Dates are represented as the number of days since 1970-01-01"

So yes, you do need to specify a day if you want to work with Date objects and benefit from all the method and the facilities that go with it

to go the other way I would suggest using the round date functionality of the package lubridate

it would change the date to the end of that week.

here is how it would work:

my_date <- as.Date("2015-01-01")

weekdays(as.Date("2015-01-01"))

"Thursday"

week_rounded_date <- lubridate::round_date(as.Date("2015-01-01"), unit = 'week')

weekdays(week_rounded_date)

"Sunday"
Mouad_Seridi
  • 2,666
  • 15
  • 27
0

You could use yearweek class in tsibble:

library(tsibble)

Avsales <- c("4500", "6000", "5500", "5000", "5100")
Week <- c("2003-23", "2003-24", "2003-25", "2003-26", "2003-27")

df <- data.frame(Week = yearweek(gsub('-',' W',Week)),Avsales = as.numeric(Avsales))
df

#      Week Avsales
#1 2003 W23    4500
#2 2003 W24    6000
#3 2003 W25    5500
#4 2003 W26    5000
#5 2003 W30    5100

library(ggplot2)
ggplot(df)+geom_line(aes(x=Week,y=Avsales))

Waldi
  • 39,242
  • 6
  • 30
  • 78