How to transform a string in Date format into R?

5

In the code below the dates are in the format: Month Day Year. I need R to recognize the variable as date.

#importa os dados
library(XML)
u<-"http://espnfc.com/team/fixtures/_/id/205/season/2012/brazil?cc=3888"
tab<-readHTMLTable(u,header=T,skip.rows=1)    
dados<-tab[[1]]

#Cria a variavel data
ano=2012
dados$DataAno<-paste(dados$Date,ano)
    
asked by anonymous 06.03.2014 / 02:13

2 answers

4

An interesting package is lubridate (CRAN) .

In your case you will use the mdy() (month, day, year) function, and say the date is in English:

library(lubridate)
dados$DataAno <- mdy(paste(dados$Date,ano), locale="en_US.UTF-8")

Note that if the date were in a different format, it would only change the order of the letters of the function, such as year, month day: ymd() (year, month, day), and so on. >     

06.03.2014 / 04:07
3

To store DataAno as Date you can change the last line to

dados$DataAno <- as.Date(paste(ano, dados$Date), format = "%Y %b %d")

format parameters are used to indicate that the string is in the format: % Y: year % b: abbreviated month (Jan, Feb, ...) % d: day (decimal between 01 and 31)

"% b" can be a problem because this depends on the region that is configured. In my case

Sys.getlocale(category = "LC_TIME")
[1] "en_US.UTF-8"
    
06.03.2014 / 02:51