我想用R语言将我的数据(时间)转换成相应的时间间隔。我的数据如下所示:
Date,Time,Lots,Status
"10-28-15","00:04:13","13-09","1"
"10-28-15","00:04:16","13-10","1"
"10-28-15","00:04:30","13-11","1"
"10-28-15","00:04:44","13-12","1"
"10-28-15","00:04:48","13-13","1"
"10-28-15","00:04:50","13-14","1"
"10-28-15","00:04:57","13-15","0"
"10-28-15","00:04:57","13-16","0"
"10-28-15","00:05:04","13-17","0"
"10-28-15","00:05:04","13-18","0"我想要这样的间隔输出(每小时4次/每15分钟)
Date,Time,Lots,Status,*interval*
"10-28-15","00:04:13","13-09","1",*"00:04:00"*
"10-28-15","00:04:16","13-10","1","00"04"15"
"10-28-15","00:04:30","13-11","1","00:04:30"
"10-28-15","00:04:44","13-12","1","00:04:45"
"10-28-15","00:04:48","13-13","1","00:04:45"
"10-28-15","00:04:50","13-14","1","00:04:45"
"10-28-15","00:04:57","13-15","0","00:04:45"
"10-28-15","00:04:57","13-16","0","00:04:45"
"10-28-15","00:05:04","13-17","0","00:05:00"
"10-28-15","00:05:04","13-18","0","00:05:00"如果我使用for循环,如
for(i=0,i<=60,i+15)
} for(if(i>i && i<=i+15)
}我怎么用R语言来做呢?谢谢你们的帮助,编程新手。
sample$int<- strptime(paste(sample$V1,sample$V2),format="%m-%d-%y %H:%M:%S")
min_V2<-trunc(min(strptime("28-10-2015 00:00:20", "%d-%m-%y %H:%M:%S")),"min")
max_V2<-trunc(max(strptime("28-10-2015 23:59:59", "%d-%m-%y %H:%M:%S")),"min") + 900
out <- cut(sample$int, breaks = seq(min_V2, max_V2, by = "15 min"))发布于 2015-11-04 07:29:19
我猜你指的是秒,而不是你想要什么的几分钟。
下面是从输入数据到15秒间隔的基本示例:
首先,将“日期”和“时间”列转换成实际的日期/时间对象:
x <- strptime(paste(mydf$Date, mydf$Time),
format = "%m-%d-%y %H:%M:%S")其次,找出值范围内的最小值和最大值。由于这些值似乎来自同一天,但使用可变分钟,我选择了"min“来截断。对于max值,我添加了60秒,直到下一分钟为止。
min_x <- trunc(min(x), "min")
max_x <- trunc(max(x), "min") + 60第三,我们可以使用seq每15秒创建一个断点序列。我们可以在cut中使用这些断点
out <- cut(x, breaks = seq(min_x, max_x, by = "15 sec"))
out
# [1] 2015-10-28 00:04:00 2015-10-28 00:04:15 2015-10-28 00:04:30
# [4] 2015-10-28 00:04:30 2015-10-28 00:04:45 2015-10-28 00:04:45
# [7] 2015-10-28 00:04:45 2015-10-28 00:04:45 2015-10-28 00:05:00
# [10] 2015-10-28 00:05:00
# 8 Levels: 2015-10-28 00:04:00 ... 2015-10-28 00:05:45第四,如果您只对时间间隔感兴趣,则可以将cut的输出格式化为日期/时间对象,并使用format仅提取小时/分钟/秒部分。
format(as.POSIXct(out), "%H:%M:%S")
# [1] "00:04:00" "00:04:15" "00:04:30" "00:04:30" "00:04:45" "00:04:45"
# [7] "00:04:45" "00:04:45" "00:05:00" "00:05:00"https://stackoverflow.com/questions/33515424
复制相似问题