如何将时间码转换为转码 [英] how to transform time codes into turn codes

查看:102
本文介绍了如何将时间码转换为转码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换这样的时间代码

I want to transform time codes like these

library(lubridate)
library(tidyverse)

df_time <- tibble(time = c(ymd_hms("2020_01_01 00:00:01"),
                           ymd_hms("2020_01_01 00:00:02"),
                           ymd_hms("2020_01_01 00:00:03"),
                           ymd_hms("2020_01_01 00:00:04"),
                           ymd_hms("2020_01_01 00:00:05"),
                           ymd_hms("2020_01_01 00:00:06")),
                  a = c(0, 1, 1, 1, 1, 0),
                  b = c(0, 0, 1, 1, 0, 0))

导致

>df_time
# A tibble: 6 x 3
  time                    a     b
  <dttm>              <dbl> <dbl>
1 2020-01-01 00:00:01     0     0
2 2020-01-01 00:00:02     1     0
3 2020-01-01 00:00:03     1     1
4 2020-01-01 00:00:04     1     1
5 2020-01-01 00:00:05     1     0
6 2020-01-01 00:00:06     0     0

转换为代码(又称事件代码/开始停止数据").应该看起来像下面的df:

into turn codes (a.k.a. event codes/"start stop data"). Should look like the following df:

df_turn <- tibble(start = c(ymd_hms("2020_01_01 00:00:02"),
                            ymd_hms("2020_01_01 00:00:03")),
                  end = c(ymd_hms("2020_01_01 00:00:05"),
                          ymd_hms("2020_01_01 00:00:04")),
                  code = c("a", "b"))


> df_turn
# A tibble: 2 x 3
  start               end                 code 
  <dttm>              <dttm>              <chr>
1 2020-01-01 00:00:02 2020-01-01 00:00:05 a    
2 2020-01-01 00:00:03 2020-01-01 00:00:04 b  


谢谢!

推荐答案

一种方法是将数据帧转换为long并滤除0.完成此操作后,您只需要每个组的最大值和最小值(根据 time ),因此我们可以在分组后使用 slice 进行操作.最后一步是使用 start end 创建一列,然后简单地将结果数据帧转换为宽格式,即

One way is to convert your data frame to long and filter out the 0s. Once you do that, you only need the maximum and minimum per group (as per time), so we can do that using slice after we group. The final step is to create a column with start and end and simply convert the resulting data frame to wide format, i.e.

library(dplyr)
library(tidyr)

df_time %>% 
 pivot_longer(cols = -1, names_to = 'code') %>% 
 filter(value != 0) %>% 
 group_by(code) %>%
 slice(c(which.min(time), which.max(time))) %>% 
 select(-value) %>% 
 mutate(new = c('start', 'end')) %>% 
 pivot_wider(names_from = new, values_from = time)

给出,

# A tibble: 2 x 3
# Groups:   name [2]
  code   start               end                
  <chr> <dttm>              <dttm>             
1 a     2020-01-01 00:00:02 2020-01-01 00:00:05
2 b     2020-01-01 00:00:03 2020-01-01 00:00:04 

这篇关于如何将时间码转换为转码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆