Devang Akotia Devang Akotia - 1 month ago 8
R Question

Convert time to character in R

I read a dataframe

dtmn
from a csv file with the following time value.

In Excel it shows:
7/4/2014 13:08


When I read it in R it shows:

> x <- dtmn[2,1]
> x
[1] 7/4/2014
Levels: 0.547222222 7/4/2014 7/4/2014 13:08 788


I would like to convert this into a character form, with the following character values:

"07/04/2014 13:08"


The function
as.character.Posixt(dtmn[2,1])
returns date only :
[1] "7/4/2014"

But I am trying to include the time also. So the desired output may look like this:
"07/04/2014 13:08"


Please help,

Answer

An easy way to solve this is using the readxl package. Suppose you have an excel file named excel_file.xlsx, and your data column is formatted as date in Excel:

date_from_excel
07/04/14 13:08
07/04/14 21:30
07/12/14 10:18

library(readxl)

df = read_excel(path=paste0("/<path-to-the-file>/",'excel_file.xlsx'), sheet=1, col_names=T, col_types=c('date') )
df = as.data.frame(df)
df$date_as_string = as.character(df$date_from_excel)

> df
  date_from_excel      date_as_string
1 2014-04-07 13:08:00 2014-04-07 13:08:00
2 2014-04-07 21:30:00 2014-04-07 21:30:00
3 2014-12-07 10:18:00 2014-12-07 10:18:00

> str(df)
'data.frame':   3 obs. of  2 variables:
 $ date_from_excel: POSIXct, format: "2014-04-07 13:08:00" "2014-04-07 21:30:00" ...
 $ date_as_string : chr  "2014-04-07 13:08:00" "2014-04-07 21:30:00" "2014-12-07 10:18:00"
Comments