Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create "Week_Start" variable in R

Tags:

date

r

I have a dataframe that look like the one below.

bus_date <- as.Date(c('2017-04-03', '2017-04-04', '2017-04-06', '2017-04-11', '2017-04-13', '2017-04-17'))
sales <- c(100, 110, 120, 200, 300, 100)


daily_sales <- data.frame(bus_date, sales)

It is a sales table at the daily level.

I want to create a new variable called "Week_Start" which is the date of the business week. I have implemented various solutions which allow me to record a week number (1-52) but I need the actual week starting date.

if (bus_date is a Monday) return(bus_date) else return(Monday before bus_date)

So my resulting dataframe would look like:

Week_Start <- as.Date(c('2017-04-03', '2017-04-03', '2017-04-03', '2017-04-10', '2017-04-10', '2017-04-17'))
daily_sales2 <- data.frame(bus_date, sales, Week_Start)

I know there is probably an easy way to do this, but unsure where to begin. Thanks.

like image 880
pyll Avatar asked Sep 11 '26 15:09

pyll


1 Answers

From ?strptime

%w Weekday as decimal number (0–6, Sunday is 0).

%W Week of the year as decimal number (00–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1). The UK convention.

as.Date(format(daily_sales$bus_date, "%Y-%W-1"), format = "%Y-%W-%w")
#[1] "2017-04-03" "2017-04-03" "2017-04-03" "2017-04-10" "2017-04-10" "2017-04-17"
like image 139
d.b Avatar answered Sep 13 '26 06:09

d.b