Search code examples
rstringdateformatcharacter

String to Date with leading X character


I'm trying to convert the Date column to date format but I keep getting an error. I think the problem might be that the date is a character and has an X before the year:

HMC.Close        Date
1     39.71 X2007.01.03
2     40.04 X2007.01.04
3     38.67 X2007.01.05
4     38.89 X2007.01.08
5     38.91 X2007.01.09
6     37.94 X2007.01.10

This is the code I've been running:

stock_honda <- expand.grid("HMC" = HMC$HMC.Close) %>%
  "Date" = as.Date(row.names(as.data.frame(HMC))) %>% 
  subset(Date >"2021-02-28" & Date < "2022-03-11")

Error in charToDate(x) : character string is not in a standard unambiguous format


Solution

  • Here is a pipeline that avoids prepending "X" to the dates in the first place:

    library(quantmod)
    getSymbols(c("FCAU.VI", "TYO", "VWAGY", "HMC"), na.rm = TRUE)
    
    library(tidyverse)
    stock_honda <- (HMC
      %>% as.data.frame()
      %>% rownames_to_column("Date")
      %>% select(Date, HMC.Close)
      %>% mutate(across(Date, lubridate::ymd))
      %>% filter(between(Date, as.Date("2021-02-28"), as.Date("2022-03-11")))
    )
    

    It would be nice if there were a version of between that avoided the need to explicitly convert to dates. (filter("2021-02-28" < Date, Date < "2022-03-11") would also work for the last step.)