4

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

Ford
  • 2,439
  • 4
  • 17
  • 15
  • 3
    R has built-in knowledge of weekdays and weekends. You don't have to keep a vector of weekend date strings. For instance, `transform(DF, weekend=as.POSIXlt(date, format='%m/%d/%Y')$wday %in% c(0, 6))` – Matthew Plourde Jun 05 '13 at 17:16

3 Answers3

5

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.

joran
  • 169,992
  • 32
  • 429
  • 468
4
DF$IsWeekend <- DF$date %in% weekend

Then if you really prefer 0s and 1s:

DF$IsWeekend <- as.numeric(DF$IsWeeekend)    
Señor O
  • 17,049
  • 2
  • 45
  • 47
1

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 ))
agstudy
  • 119,832
  • 17
  • 199
  • 261