Ford
Ford

Reputation: 2549

Creating a weekend dummy variable

I'm trying to create a dummy variable in my dataset in R for weekend i.e. the column has a value of 1 when the day is during a weekend and a value of 0 when the day is during the week.

I first tried iterating through the entire dataset by row and assigning the weekend variable a 1 if the date is on the weekend. But this takes forever considering there are ~70,000 rows and I know there is a much simpler way, I just can't figure it out.

Below is what I want the dataframe to look like. Right now it looks like this except for the weekend column. I don't know if this changes anything, but right now date is a factor. I also have a list of the dates fall on weekends:

weekend <- c("2/9/2013", "2/10/2013", "2/16/2013", "2/17/2013", ... , "3/2/2013")

date          hour          weekend
2/10/2013     0             1
2/11/2013     1             0
....          ....          ....

Thanks for the help

Upvotes: 4

Views: 4189

Answers (3)

agstudy
agstudy

Reputation: 121568

I would check if my dates are really weekend dates before.

weekends <- c("2/9/2013", "2/10/2013", "2/16/2013", "2/17/2013","3/2/2013")
weekends = weekends[ as.POSIXlt(as.Date(weekends,'%m/%d/%Y'))$wday %in% c(0,6)]

Then using trsanform and ifelse I create the new column

transform(dat ,weekend = ifelse(date %in% as.Date(weekends,'%m/%d/%Y') ,1,0 ))

Upvotes: 1

joran
joran

Reputation: 173537

It might be safer to rely on data structures and functions that are actually built around dates:

dat <- read.table(text = "date          hour          weekend
+ 2/10/2013     0             1
+ 2/11/2013     1             0",header = TRUE,sep = "")
> weekdays(as.Date(as.character(dat$date),"%m/%d/%Y")) %in% c('Sunday','Saturday')
[1]  TRUE FALSE

This is essentially the same idea as SenorO's answer, but we convert the dates to an actual date column and then simply use weekdays, which means we don't need to have a list of weekends already on hand.

Upvotes: 5

Se&#241;or O
Se&#241;or O

Reputation: 17412

DF$IsWeekend <- DF$date %in% weekend

Then if you really prefer 0s and 1s:

DF$IsWeekend <- as.numeric(DF$IsWeeekend)    

Upvotes: 4

Related Questions