0

I am all new to r programming and wanted to know if there is any way to create a function in R, which reads the day of the week and assigns 1 if it is a weekend and 0 if it is a weekday.

I have converted the date type in character format to date type and have created month, year, day, dayoftheweek, hour and min columns. I now want to create a column 'Weekend/Weekday' with 0 and 1 value.

I have used wday function so 1 is for Sunday and 7 for Saturday. If wday is 1 and 7, assign value 1 or else 0.

weekend = function(n)
  if (n$Wday == 1 || n$Wday == 7) 
    return 1
  else
    return 0
Sotos
  • 51,121
  • 6
  • 32
  • 66
Parichaya
  • 15
  • 2

1 Answers1

0

Update: This is a vectorized version of the function:

is_weekend <- function(n) {
    require(lubridate)

    (ifelse(wday(as.Date(n)) == 1, T, F) | ifelse(wday(as.Date(n)) == 7, T, F))

}    

Which results in the following Output:

df <- data.frame(date = as.Date(Sys.time()) - 0:20)

df$weekend <- is_weekend(df$date)

         date weekend
1  2019-07-16   FALSE
2  2019-07-15   FALSE
3  2019-07-14    TRUE
4  2019-07-13    TRUE
5  2019-07-12   FALSE
6  2019-07-11   FALSE
7  2019-07-10   FALSE
8  2019-07-09   FALSE
9  2019-07-08   FALSE
10 2019-07-07    TRUE
11 2019-07-06    TRUE
12 2019-07-05   FALSE
13 2019-07-04   FALSE
14 2019-07-03   FALSE
15 2019-07-02   FALSE
16 2019-07-01   FALSE
17 2019-06-30    TRUE
18 2019-06-29    TRUE
19 2019-06-28   FALSE
20 2019-06-27   FALSE
21 2019-06-26   FALSE

Since TRUE evaluate to 1 this should solve your Problem.

TimTeaFan
  • 17,549
  • 4
  • 18
  • 39