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

查看:133
本文介绍了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.

> ; 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"

但是后来我错过了时间。

But then I miss the time.

如果我愿意

> 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 

我的问题类似于

My question is similar to the question at Set time value into data frame cell

虽然花了一些时间,但对此有很好的解释

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")

第一个时间= 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天全站免登陆