R - 帮助将因子转换为日期 (%m/%d/%Y %H:%M) [英] R - Help in Converting factor to date (%m/%d/%Y %H:%M)

查看:21
本文介绍了R - 帮助将因子转换为日期 (%m/%d/%Y %H:%M)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个数据框导入 R,但 R 没有将带有日期的列识别为日期格式.

I am importing a data frame into R, but R is not recognizing the columns with the dates as being in dates format.

<代码>>我的数据[1,1][1] 2003 年 1 月 1 日 0:00216332 级别:2003 年 1 月 1 日 0:00 2003 年 1 月 1 日 0:15 2003 年 1 月 1 日 0:30 ... 2007 年 9 月 9 日 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"

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

I get what I need. However it does not work when I assign this result to my variable

> 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 

我的问题类似于 将时间值设置为数据中的问题框架单元

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

Although, it is well explained, after spending some time reading and trying I could not figure that out on my own.

推荐答案

水平意味着你有一个因素.您需要使用 as.character() 转换为字符:

The levels mean you have a factor. You need to convert to character with as.character():

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

time = 0:00 的第一项不会显示打印的时间,但其他项会.发生错误是因为 POSIXlt 对象是 11 个项目列表的列表.一般来说,使用 as.POSIXct 比使用 strptime 更好,因为 strptime 返回一个 POSIXlt 对象,而且使用起来有点混乱.:

The first item with time = 0:00 will not show the time when printed but the others will. The error is occuring because the POSIXlt object is a list of 11 item lists. Generally it is better to use as.POSIXct than to use strptime because strptime returns a POSIXlt object and they are a bit of a mess to work with.:

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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆