对于R中的循环(时间间隔)

时间:2015-11-04 06:52:06

标签: r time

我想通过使用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"))

1 个答案:

答案 0 :(得分:2)

我认为你的意思是,而不是分钟

以下是我们如何从输入数据到15秒间隔的基本示例:

首先,转换你的&#34;日期&#34;和&#34;时间&#34;用于形成实际日期/时间对象的列:

x <- strptime(paste(mydf$Date, mydf$Time), 
              format = "%m-%d-%y %H:%M:%S")

其次,找出您的值范围内的最小值和最大值。由于看起来这些值来自同一天,但随着时间的变化,我选择了#34; min&#34;截断。对于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"