Search code examples
rcharacterinsertion

Change numerical string to date format


I have the following dataframe with the date of 23/09/15 in a numerical string.

Date     Session
230915       2  
230915       2 
230915       2   
230915       2  
230915       2  
230915       2  

I want to change the "Date" column so that it's "23/09/15". Easiest way I thought to do this was to insert "/" after character 2 and 4.

I tried doing it this way:

sub( '(?<=.{2})', '/', df$Date, perl=TRUE )

But got the error:

Error in data$Date : $ operator is invalid for atomic vectors

Also tried editing the date format with:

df$Date <- as.Date(data1$Date, format="%d/%m/%Y")

The column came back with NA's. Why?


Solution

  • One way would be to use dmy from lubridate

    v1 <- dmy(df1$Date)
    v1
    #[1] "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23" "2015-09-23"
    

    It might be better to store it as Date format. But, if the format needed is different

    format(v1, "%d/%m/%y")
    #[1] "23/09/15" "23/09/15" "23/09/15" "23/09/15" "23/09/15" "23/09/15"