Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 从非分隔数据中提取小时-分钟_R_Datetime - Fatal编程技术网

R 从非分隔数据中提取小时-分钟

R 从非分隔数据中提取小时-分钟,r,datetime,R,Datetime,我有以非分隔格式包含小时和分钟的仪器数据(例如,0、30、100、130、…2300、2300)。我想将该列转换为R中的对象(例如,看起来像“2016-01-07 11:07:59 EST”),我的第一步是从该列中提取小时和分钟数据。(我还有一个对应的朱利安日期和年份列。) 我被绊倒了,因为小时和分钟没有定界,而且我无法使用strtime功能。我使用Google和SO(使用SO上的R和datatime标记)进行了搜索,但找不到解决方案。我可以在SO上找到的所有示例(例如,或)都用0:30等分隔小

我有以非分隔格式包含小时和分钟的仪器数据(例如,
0、30、100、130、…2300、2300
)。我想将该列转换为R中的对象(例如,看起来像
“2016-01-07 11:07:59 EST”
),我的第一步是从该列中提取小时和分钟数据。(我还有一个对应的朱利安日期和年份列。)

我被绊倒了,因为小时和分钟没有定界,而且我无法使用
strtime
功能。我使用Google和SO(使用SO上的
R
datatime
标记)进行了搜索,但找不到解决方案。我可以在SO上找到的所有示例(例如,或)都用
0:30
等分隔小时和分钟

这是我的MCVE:

hour <- c(0, 30, 100, 130, 1000, 1030, 2300, 2330)
year <- c(2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007)
day  <- c(2, 2, 2, 2, 2, 2, 2, 2)
strptime(hour, "%h%m")
hour试试这个:

hour <- c(0, 30, 100, 130, 1000, 1030, 2300, 2330)
year <- c(2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007)
day  <- c(2, 2, 2, 2, 2, 2, 2, 2)

mins <- substr(sprintf('%04d', hour), 3, 4)
hour <- substr(sprintf('%04d', hour), 1, 2)

as.POSIXct(paste(year, day, hour, mins, sep = ':'), format = '%Y:%d:%H:%M')

[1] "2007-01-02 00:00:00 EST" "2007-01-02 00:30:00 EST"
[3] "2007-01-02 01:00:00 EST" "2007-01-02 01:30:00 EST"
[5] "2007-01-02 10:00:00 EST" "2007-01-02 10:30:00 EST"
[7] "2007-01-02 23:00:00 EST" "2007-01-02 23:30:00 EST"

hour您可以使用
sprintf
将前导0添加到少于4位数的小时:

strptime(sprintf("%04d", hour), "%H%M")
然后可以将其转换为日期:

as.POSIXct(paste(year,day,sprintf("%04d", hour),sep="-"),format = '%Y-%j-%H%M')

使用
sprintf

as.POSIXct(sprintf("%d %d %04d", year, day, hour), "%Y %j %H%M", tz = "GMT")
#[1] "2007-01-02 00:00:00 GMT" "2007-01-02 00:30:00 GMT" "2007-01-02 01:00:00 GMT" "2007-01-02 01:30:00 GMT" "2007-01-02 10:00:00 GMT"
#[6] "2007-01-02 10:30:00 GMT" "2007-01-02 23:00:00 GMT" "2007-01-02 23:30:00 GMT"

请注意,julian days是用
%j
指定的,而不是
%d

一种可能的解决方案是用“stringr”中的“str_pad”填充足够的0,然后使用“strTime”:

tmp <- stringr::str_pad(hour,4,"left","0")
strptime(tmp, "%H%M")

tmp这很接近……但忽略分钟数。另外,我不知道如何解释会议记录。100-1:00还是10:00?as.POSIXct(粘贴(年、日、小时、九月=':'),格式='%Y:%d:%H')感谢您向我展示
sprintf
函数。那是关键!(在你删除之前,我也看到了你的评论)。