Alex.V
Alex.V

Reputation: 55

How to convert a character column into date using as.POSIXct?

I have a problem. I have a data frame (data.in) with 3 columns (date| wd |ws ) and using str() command gives me character for column "date". Ok, I said I will use function : as.POSIXct(data.in$date, format = "%m/%d/%Y %H:%M" ). It doesn't give NA values but the date column remains character format and it doesn't convert to date format.

data.in <- read.csv(file = "/home/vlad/Documents/vldZ/R_meteo/20130101.csv",
col.names = c("date","hr","ws.80","wd.80"), stringsAsFactors = FALSE)
data.in$data <- paste(data.in$date,data.in$hr) data.in[1:2] <- NULL 

colnames(data.in)[3] <- "date" 
as.Date(data.in$data,format = "%m/%d/%Y ") 
as.POSIXct(data.in$date, format = "%m/%d/%Y %H:%M" ) #### my code 

Upvotes: 1

Views: 1507

Answers (1)

maaniB
maaniB

Reputation: 605

You may use different functions to make your time/date variables. Pay attention to the typeof (i.e., data storage mode in the memory) and class (i.e., object classes):

date1 <- as.Date(
  c("2019-01-01 14:22","2019-01-01 16:08", "2019-01-01 07:16"), 
  format = "%Y-%m-%d %H:%M"
  )
> typeof(date1)
[1] "double"
> class(date1)
[1] "Date"


date2 <- as.POSIXct(
  c("2019-01-01 14:22","2019-01-01 16:08", "2019-01-01 07:16"), 
  format = "%Y-%m-%d %H:%M"
)
> typeof(date2)
[1] "double"
> class(date2)
[1] "POSIXct" "POSIXt" 


date3 <-  strptime(
  c("2019-01-01 14:22","2019-01-01 16:08", "2019-01-01 07:16"), 
  format = "%Y-%m-%d %H:%M"
)
> typeof(date3)
[1] "list"
> class(date3)
[1] "POSIXlt" "POSIXt" 

They may be shown as in double quotes " ":

[1] "2019-01-01 14:22:00 +0330" "2019-01-01 16:08:00 +0330"
[3] "2019-01-01 07:16:00 +0330"

But they do not have a character typeof.

Upvotes: 1

Related Questions