r

时间:2017-05-31 21:55:59

标签: r reshape2 dcast

> log_df[1:10, ]
      tagid            happened status
1  03B2ACE7 2016-06-28 18:07:36   open
2  03B2ACE7 2016-06-28 18:36:15 closed
3  03B2ACE7 2016-06-29 07:29:59   open
4  03B2ACE7 2016-06-29 08:06:23 closed
5  03B2ACE7 2016-06-30 16:10:48   open
6  03B2ACE7 2016-06-30 17:23:55   open
7  03B2ACE7 2016-07-01 10:12:06 closed
8  03B2ACE7 2016-07-01 13:39:58 closed
9  03B2ACE7 2016-07-02 10:08:40   open
10 03B2ACE7 2016-07-02 13:33:01 closed
...

以上是我的数据。 我想要制作的是:

      tagid                open               closed
1  03B2ACE7 2016-06-28 18:07:36  2016-06-28 18:36:15
2  03B2ACE7 2016-06-29 07:29:59  2016-06-29 08:06:23
3  03B2ACE7 2016-06-30 16:10:48  2016-07-01 10:12:06
...

我试图在reshape2包中使用dcast。 但是,我必须选择性地选择

“打开”,这是第一个,只有那些在关闭之后出现并且在关闭之前出现的“关闭”。

因此,从log_df开始,第6行和第7行将被忽略..

我真的被卡住了,不知道我怎么能这样做.. 也许dcast不是最好的方法?

请帮忙!非常感谢你!

1 个答案:

答案 0 :(得分:1)

使用dplyrtidyr(来自tidiverse,重塑的演变):

library(dplyr)
library(tidyr)

df %>% 
    filter((status == 'open' & lag(status, default = "") != 'open') | (status == 'closed' & lead(status, default = "") != "closed")) %>% 
    mutate(r = ceiling(row_number() / 2)) %>% 
    spread(status, happened)

#>      tagid r              closed                open
#> 1 03B2ACE7 1 2016-06-28 18:36:15 2016-06-28 18:07:36
#> 2 03B2ACE7 2 2016-06-29 08:06:23 2016-06-29 07:29:59
#> 3 03B2ACE7 3 2016-07-01 13:39:58 2016-06-30 16:10:48
#> 4 03B2ACE7 4 2016-07-02 13:33:01 2016-07-02 10:08:40

它:

  1. 使用特定条件过滤data.frame
  2. 添加一列以存储&#39; <&#39;
  3. 将值传播到列(相当于dcast)
  4. 数据:

    df <- read.table(text = '      tagid            happened status
    1  03B2ACE7 "2016-06-28 18:07:36"   open
    2  03B2ACE7 "2016-06-28 18:36:15" closed
    3  03B2ACE7 "2016-06-29 07:29:59"   open
    4  03B2ACE7 "2016-06-29 08:06:23" closed
    5  03B2ACE7 "2016-06-30 16:10:48"   open
    6  03B2ACE7 "2016-06-30 17:23:55"   open
    7  03B2ACE7 "2016-07-01 10:12:06" closed
    8  03B2ACE7 "2016-07-01 13:39:58" closed
    9  03B2ACE7 "2016-07-02 10:08:40"   open
    10 03B2ACE7 "2016-07-02 13:33:01" closed', h = T)