R-将变量格式从int更改为hour

  • 本文关键字:hour int 变量 格式 r time
  • 更新时间 :
  • 英文 :


我在数据帧中有一列,其中报告了事件发生的小时数。只是时间,而不是几分钟或几秒钟。这是一个整数格式,但我想让R读它作为一个小时(时间)。我已经检查了as的文档。日期,但没有什么可以帮助我的。

我尝试了以下命令,但它返回了一条错误消息:

> attach(data)
> Hour <- as.Date(Hour, "%H")

但它返回以下错误消息:

Error in charToDate(x) : 
character string is not in a standard unambiguous format

非常感谢,

Gianluca

日期对象是时间点,一天和一天中的时间也是时间点。

如果你想将一个小时格式化为一个好的格式,请使用sprintf:

sprintf("%02d:00",1:24)
[1] "01:00" "02:00" "03:00" "04:00" "05:00" "06:00" "07:00" "08:00" "09:00"
[10] "10:00" "11:00" "12:00" "13:00" "14:00" "15:00" "16:00" "17:00" "18:00"
[19] "19:00" "20:00" "21:00" "22:00" "23:00" "24:00"

但只在你想要漂亮的输出时才这样做,而不是为了计算。

还有另一个想法。为小时整数创建一个类。。。

> h = 1:24
> class(h)="hours"
> h
[1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
attr(,"class")
[1] "hours"

到目前为止所做的只是添加"class"属性。让我们写一个格式方法:

format.hours<- function(x,...){sprintf("%02d:00",x)}
format.hours(h)
[1] "01:00" "02:00" "03:00" "04:00" "05:00" "06:00" "07:00" "08:00" "09:00"
[10] "10:00" "11:00" "12:00" "13:00" "14:00" "15:00" "16:00" "17:00" "18:00"
[19] "19:00" "20:00" "21:00" "22:00" "23:00" "24:00"

我们不想一直输入format,所以让我们把它挂在打印函数中:

> print.hours <- function(x,...){print(format(x))}
> h
[1] "01:00" "02:00" "03:00" "04:00" "05:00" "06:00" "07:00" "08:00" "09:00"
[10] "10:00" "11:00" "12:00" "13:00" "14:00" "15:00" "16:00" "17:00" "18:00"
[19] "19:00" "20:00" "21:00" "22:00" "23:00" "24:00"

太好了。我们还可以使用小时类向量制作数据帧列:

df = data.frame(h = as.numeric(h),x=runif(24)) ; class(df$h)="hours"
df
h          x
1  01:00 0.74339236
2  02:00 0.61240165
3  03:00 0.65007809
4  04:00 0.24844327
5  05:00 0.80499618

如果您编写更多的数据帧方法,可以使最后一个示例更好地工作。

然后,您可以继续为hour类编写算术方法,这样添加hours就不会变成24(它只是mod 24的算术运算),或者您可以将其修改为包括分钟、秒,并打包一大堆时钟时间处理代码。。。。

但我在这里飞得很快。。。。

我建议您从lubridate包开始(http://cran.r-project.org/web/packages/lubridate/index.html),具有一系列周到的时间处理功能。你可能最终不会使用它们,但这些文档肯定会让你思考整个问题,你肯定会觉得有用。

例如,您可以显式表示工期,然后将其与传统的时间表示结合使用,例如Date或time类:

> dminutes(3)
[1] "180s (~3 minutes)"
> Sys.Date()
[1] "2013-12-31"
> Sys.Date() - dminutes(3)
[1] "2013-12-30 23:57:00 UTC"

文件显示,

"Details
When paired with date-times, these functions allow date-times to be manipulated in a method similar to object oriented programming. Period objects can be added to Date, POSIXct, and POSIXlt objects to calculate new date-times."

最新更新