如何使用as.POSIXct将字符列转换为日期?

时间:2019-08-22 08:29:49

标签: r date posixct

我有问题。我有一个包含3列(date | wd | ws)的数据框(data.in),并且使用str()命令给我列“ date”的字符。好的,我说过我将使用功能:as.POSIXct(data.in$date, format = "%m/%d/%Y %H:%M" )。它不提供NA值,但date列仍为字符格式,并且不会转换为日期格式。

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 

1 个答案:

答案 0 :(得分:1)

您可以使用其他函数来设置时间/日期变量。请注意typeof,内存中的数据存储模式)和class i.e。对象类):

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" 

它们可能显示为双引号" "

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

但是他们没有character型的。