您可以使用将字符向量转换为日期时间格式ymd_hms
的函数lubridate
包裹:
library(lubridate)
# data frame simulation
structure(list(X1 = c(1, 1, 1, 1, 1, 1), X1.1 = c(1, 1, 1, 1, 1, 1),
X1.2 = c(1, 1, 1, 1, 1, 1), X1.3 = c(1, 1, 1, 1, 1, 1),
X1.4 = c(1, 1, 1, 1, 1, 1), date_time_char = c("2014-12-22 23:53:48",
"2014-12-22 23:20:34", "2014-12-22 23:20:30", "2014-12-22 23:20:16",
"2014-12-22 23:20:07", "2014-12-22 23:05:49")), class = "data.frame", row.names = c(NA, -6L))
# transform from character to datetime
data$date_time <- ymd_hms(data[, 6])
data[, 7]
Output:
[1] "2014-12-22 23:53:48 UTC" "2014-12-22 23:20:34 UTC" "2014-12-22 23:20:30 UTC" "2014-12-22 23:20:16 UTC"
[5] "2014-12-22 23:20:07 UTC" "2014-12-22 23:05:49 UTC"
注意:大卫·阿伦堡 (David Arenburg) 的评论非常好:
这实际上是一个好问题。这不是一个错误,而是一个
警告,但你得到的结果是错误的,所以你可以将其视为
一个错误。发生这种情况的原因是因为定义
R中的矩阵,只能得到原子向量。当你尝试的时候
将 strptime 传递给矩阵,它的类是“POSIXlt”“POSIXt”,因此
它取消了它的类,从而返回它的属性列表(其中
length 大于 1),即 unclass(strptime(data[1,1],"%F %T"))。
第一个值是 48 秒。这正是你所拥有的
现在是 temp_file[1]。