How to know the day of the week in R?

6

Is there a package or function in R that lets you easily get the day of the week from the dates?

datas <- c("2010-06-28", "2011-05-25", "2010-09-28", "2011-12-05", "2010-09-14", 
           "2010-01-01", "2010-01-02", "2010-01-03", "2010-01-04", "2010-01-04", 
           "2010-01-04", "2010-01-05", "2010-01-05", "2010-01-05", "2010-01-07", 
           ) 
    
asked by anonymous 20.01.2016 / 14:46

2 answers

4

To format dates in general you can use the format() function. The functions weekdays() and months() , for example, in the background are wrappers for format() .

To extract the day of the week you will ask for %a or %A , depending on whether you want the abbreviated day of the week or not:

datas <- c("2010-06-28", "2011-05-25", "2010-09-28", "2011-12-05", "2010-09-14", 
           "2010-01-01", "2010-01-02", "2010-01-03", "2010-01-04", "2010-01-04", 
           "2010-01-04", "2010-01-05", "2010-01-05", "2010-01-05", "2010-01-07") 

format.Date(as.Date(datas), "%a") # abreviado
[1] "seg" "qua" "ter" "seg" "ter" "sex" "sáb" "dom" "seg" "seg" "seg" "ter" "ter" "ter" "qui"

format.Date(as.Date(datas), "%A") 
 [1] "segunda-feira" "quarta-feira"  "terça-feira"   "segunda-feira" "terça-feira"  
 [6] "sexta-feira"   "sábado"        "domingo"       "segunda-feira" "segunda-feira"
[11] "segunda-feira" "terça-feira"   "terça-feira"   "terça-feira"   "quinta-feira" 

The two functions are equivalent to:

weekdays(as.Date(datas), abbreviate = TRUE)
weekdays(as.Date(datas))

I put the format because if you want to get more things beyond the day of the week is easier. For example:

format.Date(as.Date(datas), "%a, %d de %B de %Y")
 [1] "seg, 28 de junho de 2010"    "qua, 25 de maio de 2011"     "ter, 28 de setembro de 2010"
 [4] "seg, 05 de dezembro de 2011" "ter, 14 de setembro de 2010" "sex, 01 de janeiro de 2010" 
 [7] "sáb, 02 de janeiro de 2010"  "dom, 03 de janeiro de 2010"  "seg, 04 de janeiro de 2010" 
[10] "seg, 04 de janeiro de 2010"  "seg, 04 de janeiro de 2010"  "ter, 05 de janeiro de 2010" 
[13] "ter, 05 de janeiro de 2010"  "ter, 05 de janeiro de 2010"  "qui, 07 de janeiro de 2010" 
    
20.01.2016 / 17:46
3
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02")) 
df$day <- weekdays(as.Date(df$date))
df

##      data       dia
## 1 2012-02-01   Quarta
## 2 2012-02-01   Quarta
## 3 2012-02-02   Quinta
    
20.01.2016 / 14:54