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

R-将变量格式从int更改为hour,r,time,R,Time,我在数据框中有一列,其中报告了事件发生的时间。只有小时,而不是分钟或秒。 这是一个整数格式,但我想让R读取它作为一个小时(时间)。我已经检查了as.Date的文档,但是没有任何东西可以帮助我 我已尝试使用以下命令,但它返回错误消息: > attach(data) > Hour <- as.Date(Hour, "%H") Error in charToDate(x) : character string is not in a standard unambiguous

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

我已尝试使用以下命令,但它返回错误消息:

> attach(data)
> Hour <- as.Date(Hour, "%H")
Error in charToDate(x) : 
  character string is not in a standard unambiguous format
非常感谢,


吉安卢卡

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

如果您想将小时设置为一个好的格式,请使用
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"
好极了。我们还可以使用小时类向量制作数据帧列:

 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 airthmetic),或者您可以修改它以包含分钟、秒,并打包一整套时钟时间处理代码


但是我在这里的处理非常好……

我想建议您从
lubridate
包()开始,它有一系列经过深思熟虑的时间处理函数。您可能最终不会使用它们,但文档肯定会让您思考整个问题,您肯定会发现这很有用

例如,您可以显式表示持续时间,然后将其与传统的时间表示(如日期或时间类)结合使用:

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

你认为数字数据和小时数据有什么区别?没有称为
hours
的固有类型,它必须是包含完整日期的时间的一部分…好的,那么在处理它时R没有区别吗?我只是愿意使用正确的格式。我是个初学者,所以我没有完全意识到它可能有什么不同。我只是想得到尽可能小的数据集。您显示的错误是有意义的。如果只指定一天中的小时,则日期不可能存在(事实上,
date
没有小时,
time
有小时(
?POSIXct
)。根据最终目标,将小时视为数字可能是最好的方法。可能类似于
strtime(as.integer(c(1,5,14)),format=“%H”)+3600
是有帮助的?(
+3600
部分只是显示
'+.POSIXt'
方法,即“R读为小时”)。啊,但这些是持续时间(例如“持续了六小时十分钟”),而不是一天中的时间(例如“每天早上六点十分发生一次”)这就是OP的工作。我有一种感觉,在某处有一个处理时钟时间的软件包。。。
"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."