R - 帮助将因子转换为日期 (%m/%d/%Y %H :%M)

标签 r date dataframe type-conversion

我正在将数据框导入到 R 中,但 R 无法将带有日期的列识别为日期格式。

> mydata[1,1] [1] 2003年1月1日 0:00 216332 级别: 1/1/2003 0:00 1/1/2003 0:15 1/1/2003 0:30 ... 9/9/2007 9:55

我尝试过:

> as.Date(mydata[1,1], format = "%m/%d/%Y %H:%M")
[1] "2003-01-01"

但后来我错过了时间。

如果我这样做

> strptime(mydata[2,1], format = "%m/%d/%Y %H:%M")
[1] "2003-01-01 00:15:00 EST"

我得到了我需要的东西。但是,当我将此结果分配给我的变量时,它不起作用

> mydata[,1] <- strptime(mydata[,1], format = "%m/%d/%Y %H:%M")
Warning message:
In `[<-.data.frame`(`*tmp*`, , 1, value = list(sec = c(0, 0, 0,  :
  provided 11 variables to replace 1 variables 

我的问题与 Set time value into data frame cell 中的问题类似

尽管解释得很好,但在花了一些时间阅读和尝试后,我自己无法弄清楚。

最佳答案

这些级别意味着您有一个因素。您需要使用 as.character() 转换为字符:

 dt <- as.POSIXct(as.character(mydata[ ,1]) format = "%m/%d/%Y %H:%M")

第一个时间 = 0:00 的项目在打印时不会显示时间,但其他项目会显示时间。发生错误的原因是 POSIXlt 对象是包含 11 个项目列表的列表。一般来说,使用 as.POSIXct 比使用 strptime 更好,因为 strptime 返回一个 POSIXlt 对象,并且使用它们有点困惑。:

d <- factor("1/1/2003 0:01")
as.POSIXct( as.character(d), format = "%m/%d/%Y %H:%M")
[1] "2003-01-01 00:01:00 PST"

关于R - 帮助将因子转换为日期 (%m/%d/%Y %H :%M),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24497847/

相关文章:

r - excel函数“R中决策函数的搜索

r - 如何在 R 中保存绘图图像?

mysql - 如何在mysql中过滤日期?

r - 将嵌套列表中的元素转换为数据框

r - 从data.frame创建条形图

r - Filled.contour 与 ggplot2 + stat_contour

sql - 从多列中生成日期

php - MYSQL在屏幕上分段打印日期

python - 解析数据框

r - 循环遍历 data.tables 列表时如何对行进行子集化?