How to turn a string into Date format in R?

Asked

Viewed 4,567 times

7

In the code below the dates are in the format: Mes Dia Ano. 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)

2 answers

6


An interesting package is the lubridate (CRAN).

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

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

Note that if the date was in different format it would be enough to change the order of the function’s letters, for example, year, day month:ymd() (year, Month, day), and so on.

4

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

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

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

"%b" may be a problem because it depends on which region is configured. In my case

Sys.getlocale(category = "LC_TIME")
[1] "en_US.UTF-8"

Browser other questions tagged

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