How to know the day of the week in R?

Asked

Viewed 1,558 times

6

Is there a package or function in R that allows to easily obtain the day of the week from 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", 
           ) 

2 answers

4


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

To extract the day of the week you will ask %a or %A, depending on whether you want the day of the week shortened 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" 

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
  • 3

    Offer a little more detail to the Questioner, so the answer will be for future research!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.