1

My date format is "Sat 12 Sep" as character. I want to transform it into Date format in a new column called DATE.

mutate(DATE = (as.Date(FECHA, "%a %d %b")))

but it returns NA

 X      FECHA        LOCAL       RESULT   VISITANTE       DATE      
 <int>  <chr>        <fct>       <fct>    <fct>           <date>    
 1      3 **Sat 12 Sep** Eibar   0 - 0    Celta Vigo      NA        
 2      4 Sat 12 Sep Granada     2 - 0    Athletic Bilbao NA 

Thanks

makeyourownmaker
  • 1,558
  • 2
  • 13
  • 33

2 Answers2

0

I would recommend looking at the lubridate package. It will add 2020 as the year automatically (be careful if that is not what you want).

See if this works for you:

library(lubridate)

x <- "Sat 12 Sep"

parse_date_time(x, "%a %d %b", locale = "UK")
[1] "2020-09-12 UTC"
L Smeets
  • 888
  • 4
  • 17
0

Here is a solution using base with data.frame for your sample data and as.Date to convert from the FECHA variable from character to date.

Code:

Sys.setlocale("LC_TIME", "English")

df <- data.frame(X = as.integer(c(3, 4)),
                 FECHA = as.character(c("Sat 12 Sep", "Sat 12 Sep")),
                 LOCAL = as.factor(c("Eibar", "Granada")),
                 RESULT = as.factor(c("0 - 0", "2 - 0")),
                 VISITANTE = as.factor(c("Celta Vido", "Athletic Bilbao")),
                 DATE = as.Date(c(NA, NA)))

df$DATE <- as.Date(df$FECHA, format = "%a %d %B")

Output:

#>   X      FECHA   LOCAL RESULT       VISITANTE       DATE
#> 1 3 Sat 12 Sep   Eibar  0 - 0      Celta Vido 2020-09-12
#> 2 4 Sat 12 Sep Granada  2 - 0 Athletic Bilbao 2020-09-12

Created on 2020-10-19 by the reprex package (v0.3.0)

Original Output:

#>   X      FECHA   LOCAL RESULT       VISITANTE DATE
#> 1 3 Sat 12 Sep   Eibar  0 - 0      Celta Vido <NA>
#> 2 4 Sat 12 Sep Granada  2 - 0 Athletic Bilbao <NA>

Created on 2020-10-19 by the reprex package (v0.3.0)

Eric
  • 2,699
  • 5
  • 17
  • 1
    This won't work in OP's locale. The issue is that an English locale is needed to parse "Sat" and "Sep". The character method of `as.Date` doesn't have a `tz` parameter (which only affects the time zone anyway, not the locale). – Roland Oct 19 '20 at 13:46
  • @Roland - Do you mind if I borrow from your comment and add it to my solution? `Sys.setlocale("LC_TIME", "English")` before the code for a locale-specific version of the date. – Eric Oct 19 '20 at 13:50