Creating a variable for output files

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

At first I tried to iterate over the entire dataset on a row and assign the weekend variable 1 if the date is on the weekend. But this requires forever, because there are ~ 70,000 lines, and I know that there is a much simpler way, I just can not understand.

Below I want the dataframe core to look. Now it looks, except for the weekend column. I do not know if this will change anything, but now the date is a factor. I also have a list of weekend dates:

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

+4
source share
3 answers
 DF$IsWeekend <- DF$date %in% weekend 

Then if you really prefer 0s and 1s:

 DF$IsWeekend <- as.numeric(DF$IsWeeekend) 
+4
source

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 the actual date column and then just use weekdays , which means we don’t need to have a list of holidays at hand.

+5
source

I would check if my dates were really weekend dates.

 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 a new column

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

Source: https://habr.com/ru/post/1484688/


All Articles