Home > Enterprise >  How can I convert a column of date/time data from numeric to character in R?
How can I convert a column of date/time data from numeric to character in R?

Time:10-13

I have a column of data compiled from Excel files. Some of the values in the date column have changed upon binding and are now numeric date format (despite their starting out character) whilst others remain as they were (yyyy-mm-dd hh:mm). How can I change the entire column to the same date format (yyyy-mm-dd hh:mm)? Thanks in advance.

CodePudding user response:

Try strptime:

df$column <- strptime(df$column, format='%Y-%m-%d %H:%M')

CodePudding user response:

OK so I finally cracked it. This is probably very obvious to everyone but just in case a newb like myself has this same issue this is what solved it for me. I had two sets of data that I'd bound into the same table. One set of data came from XLSX files and the other from CSV files. They both presented fine in R but when combined the CSV-derived lost formatting and reverted to numerical dates. I discovered that the 'date' columns in the xlsx-derived tables were 'character' whilst the 'date' columns in the csv-derived tables were 'factor with 1 level'. When combined, the character data preserved format (i.e. looked like a date - yyyy-mm-dd hh:mm) and the factor data turned into numeric dates

So to rectify I used the following on the .csv (factor) tables before binding:

    myfile$Date <- as.character(myfile$Date)   
 

This changed the columns to character to match the others and the bind was successful and all date formatting was preserved. Thank you for your help!

  • Related