Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/79.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
获取标志的开始时间和结束时间=1,如果它重复4次(不使用for循环)_R - Fatal编程技术网

获取标志的开始时间和结束时间=1,如果它重复4次(不使用for循环)

获取标志的开始时间和结束时间=1,如果它重复4次(不使用for循环),r,R,我是R新手,一直在获取Flag=1的开始时间和结束时间。条件是,1应至少重复(连续)4次,然后只需捕获其开始和结束时间。我的输入看起来像- 时间戳标志 00:00:00 1 00:00:10 1 00:00:20 1 00:00:30 1 00:00:40 0 00:00:50 0 00:01:00 0 00:01:10 0 00:01:20 0 00:01:30

我是R新手,一直在获取Flag=1的开始时间和结束时间。条件是,1应至少重复(连续)4次,然后只需捕获其开始和结束时间。我的输入看起来像-

时间戳标志
00:00:00        1
00:00:10        1
00:00:20        1
00:00:30        1
00:00:40        0
00:00:50        0
00:01:00        0
00:01:10        0
00:01:20        0
00:01:30        1
00:01:40        1
00:01:50        1
00:02:00        0
00:02:10        1
00:02:20        1
00:02:30        1
00:02:40        1
00:02:50        1
00:03:00        1
00:03:10        1
00:03:20 1

我的输出应该是-

开始时间结束时间持续时间
00:00:00    00:00:30    00:00:30
00:02:10 00:03:20 00:01:10

我使用for循环和if-else实现了它,但由于数据量巨大,需要花费大量时间。所以,我需要优化它


R中是否有我可以修改和使用的内置函数?

首先使用以下方法创建数据:

st <- data.frame(Time = format(seq(from=as.POSIXct("2012-1-1 00:00:00", tz="UTC"),
                                     to=as.POSIXct("2012-1-1  00:03:20", tz="UTC"), 
                               by="10 secs") , "%H:%M:%S" ), 
                 Flag = c(1,1,1,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1))

st$Time <- as.POSIXct(st$Time, format = "%H:%M:%S")
结果是

# A tibble: 2 × 4
     gr          start.time           last.time Duration
  <int>              <dttm>              <dttm>   <time>
1     0 2017-06-08 00:00:00 2017-06-08 00:00:30  30 secs
2     4 2017-06-08 00:02:10 2017-06-08 00:03:20  70 secs
#一个tible:2×4
gr start.time last.time持续时间
1 0 2017-06-08 00:00:00 2017-06-08 00:00:30 30秒
24 2017-06-08 00:02:10 2017-06-08 00:03:20 70秒

首先使用以下方法创建数据:

st <- data.frame(Time = format(seq(from=as.POSIXct("2012-1-1 00:00:00", tz="UTC"),
                                     to=as.POSIXct("2012-1-1  00:03:20", tz="UTC"), 
                               by="10 secs") , "%H:%M:%S" ), 
                 Flag = c(1,1,1,1,0,0,0,0,0,1,1,1,0,1,1,1,1,1,1,1,1))

st$Time <- as.POSIXct(st$Time, format = "%H:%M:%S")
结果是

# A tibble: 2 × 4
     gr          start.time           last.time Duration
  <int>              <dttm>              <dttm>   <time>
1     0 2017-06-08 00:00:00 2017-06-08 00:00:30  30 secs
2     4 2017-06-08 00:02:10 2017-06-08 00:03:20  70 secs
#一个tible:2×4
gr start.time last.time持续时间
1 0 2017-06-08 00:00:00 2017-06-08 00:00:30 30秒
24 2017-06-08 00:02:10 2017-06-08 00:03:20 70秒