Search code examples
rdatetime-formatdate-conversion

How do I convert values like this to date type in R?


I have a data frame with a "date" (factor with different levels) column with values like X3.5.20, x3.6.20, x3.7.20, and so on. This is in the format (month.date.year).

My question is how can I convert this to a date variable in R?


Solution

  • R does not let the column names to start with numbers by default hence 'X' is added at the beginning, however, you can avoid that by using check.names = FALSE when importing the dataframe. If you have csv named data.csv, you can do

    df <- read.csv('data.csv', check.names = FALSE)
    

    If you have already imported the data you can change the column names by

    names(df) <- as.Date(names(df), 'X%m.%d.%y')