当我需要从时间变量中提取小时时出错

时间:2018-05-04 09:22:36

标签: r date

我有一个有时间值的向量

> head(DataCRMSanoflore$Heure.Inscription)
[1] 12:59:45 10:57:12 13:46:39 13:08:26 11:00:21 13:25:13
20760 Levels:  00:00:12 00:00:17 00:00:18 00:00:27 00:00:32 00:00:38 00:00:42 00:00:48 00:00:51 00:00:53 00:00:55 00:01:00 00:01:07 ... Letellier

然后我需要提取每个值的小时。所以我使用了这段代码:

DataCRMSanoflore$HOURS_INSCR<-hour(hms(as.character(DataCRMSanoflore$Heure.Inscription)))

但是我收到了一个错误:

  

as.POSIXlt.numeric(x)出错:&#39; origin&#39;必须提供       另外:警告信息:       在.parse_hms(...,order =&#34; HMS&#34;,quiet = quiet):         某些字符串无法解析,或者所有字符串都是NA

提前谢谢

2 个答案:

答案 0 :(得分:1)

试试这个解决方案:

输入数据:

h<-c("12:59:45","10:57:12","13:46:39","13:08:26","11:00:21","13:25:13")

提取第一个值(小时)并将其合并为小时格式

hour(as.POSIXct(unlist(lapply(strsplit(h,":"),"[",1)),format="%H"))
[1] 12 10 13 13 11 13

答案 1 :(得分:0)

vec<-c("12:59:45","10:57:12","13:46:39","13:08:26","11:00:21","13:25:13") 

unclass(as.POSIXlt(vec,format = "%T"))$h
[1] 12 10 13 13 11 13

lubridate::hour(as.POSIXlt(vec,format = "%T"))
[1] 12 10 13 13 11 13