根据不同的列重塑数据

Reshape Data based on Different columns

我需要重塑我的数据,以适合生存分析的格式获取它。

我当前的数据集如下所示:

Product_Number            Date         Status 
     A                  2018-01-01        0
     A                  2018-01-02        1
     A                  2018-01-03        0
     B                  2018-01-01        0
     B                  2018-01-02        0
     B                  2018-01-03        0
     B                  2018-01-04        1
     C                  2018-01-01        0
     C                  2018-01-02        0

我需要根据 Product_Number、日期和状态列重塑我的数据(我想计算每个产品的天数,直到状态变为 1。如果状态是0,过程应该重新开始)。

所以数据应该是这样的:

Product_Number    Number_of_Days    Status 
       A                2             1    #Two days til status = 1
       A                1             0    #One day, status = 0 (no end date yet) 
       B                4             1    #Four days til status = 1
       C                2             0    #Two days, status is still 0 (no end date yet)

到目前为止我尝试了什么?

我按产品编号和日期订购了我的数据。我喜欢 DPLYR 方式,所以我使用了:

df <- df %>% group_by(Product_Number, Date)   # note: my data is now in the form as in the example above. 

然后我尝试使用 diff() 函数来查看日期差异(计算天数)。但是当状态切换时(从 0 到 1,反之亦然),我无法 "stop" 计数。

希望我把问题解释清楚了。如果您需要一些其他信息,请告诉我。

如果我答对了你的问题,这可能就是你要找的。

library(dplyr)

df %>%
  mutate(Number_of_Days=1) %>%
  select(-Date) %>%
  group_by(Product_Number, Status) %>%
  summarise_all(sum,na.rm=T)

  Product_Number Status Number_of_Days
1 A                   0              2
2 A                   1              1
3 B                   0              3
4 B                   1              1
5 C                   0              2

你可以这样做:

library(dplyr)

df %>%
  group_by(Product_Number) %>%
  mutate(Date = as.Date(Date),
         group = cumsum(coalesce(as.numeric(lag(Status) == 1 & Status == 0), 1))) %>%
  group_by(Product_Number, group) %>%
  mutate(Number_of_Days = (last(Date) - first(Date)) + 1) %>%
  slice(n()) %>% ungroup() %>%
  select(-group, -Date)

输出:

# A tibble: 4 x 3
  Product_Number Status Number_of_Days
  <chr>           <int> <time>        
1 A                   1 2             
2 A                   0 1             
3 B                   1 4             
4 C                   0 2