将每个组的product_id乘以12个月

时间:2019-02-19 10:35:06

标签: r dplyr data.table lubridate

说我有这个数据

mydat <- structure(list(product_id = 11511:11512, coef = c(1L, 1L)), 
                   .Names = c("product_id", "coef"), class = "data.frame", 
                   row.names = c(NA, -2L))

在系数重复的情况下,如何将每个组的product_id乘以12个月 即期望的输出

   product_id   months coef
1       11511 2018-jan    1
2       11511 2018-feb    1
3       11511 2018-mar    1
4       11511 2018-apr    1
5       11511 2018-may    1
6       11511 2018-jun    1
7       11511 2018-jul    1
8       11511 2018-aug    1
9       11511 2018-sep    1
10      11511 2018-oct    1
11      11511 2018-nov    1
12      11511 2018-dec    1
13      11512 2018-jan    1
14      11512 2018-feb    1
15      11512 2018-mar    1
16      11512 2018-apr    1
17      11512 2018-may    1
18      11512 2018-jun    1
19      11512 2018-jul    1
20      11512 2018-aug    1
21      11512 2018-sep    1
22      11512 2018-oct    1
23      11512 2018-nov    1
24      11512 2018-dec    1

2 个答案:

答案 0 :(得分:2)

使用data.table的一种方式:

library(data.table)

mydat <- setDT(mydat)[, .(product_id = product_id,
                          months = format(seq(as.Date("2018-01-01"), 
                                              as.Date("2018-12-31"), 
                                              by = "month"), "%Y-%b"),
                          coef = coef), by = 1:nrow(mydat)][, nrow := NULL]

输出:

    product_id   months coef
 1:      11511 2018-Jan    1
 2:      11511 2018-Feb    1
 3:      11511 2018-Mar    1
 4:      11511 2018-Apr    1
 5:      11511 2018-May    1
 6:      11511 2018-Jun    1
 7:      11511 2018-Jul    1
 8:      11511 2018-Aug    1
 9:      11511 2018-Sep    1
10:      11511 2018-Oct    1
11:      11511 2018-Nov    1
12:      11511 2018-Dec    1
13:      11512 2018-Jan    1
14:      11512 2018-Feb    1
15:      11512 2018-Mar    1
16:      11512 2018-Apr    1
17:      11512 2018-May    1
18:      11512 2018-Jun    1
19:      11512 2018-Jul    1
20:      11512 2018-Aug    1
21:      11512 2018-Sep    1
22:      11512 2018-Oct    1
23:      11512 2018-Nov    1
24:      11512 2018-Dec    1

答案 1 :(得分:1)

library(dplyr)
library(tidyr)
mydat %>% mutate(month=1) %>% 
          complete(product_id,coef, nesting(month=1:12)) %>%
          mutate(month=as.Date(paste0('2018-',month,'-01')))

# A tibble: 24 x 3
    product_id  coef month         
         <int> <int> <date>    
  1      11511     1 2018-01-01
  2      11511     1 2018-02-01
  3      11511     1 2018-03-01
  4      11511     1 2018-04-01
  5      11511     1 2018-05-01
  6      11511     1 2018-06-01
  7      11511     1 2018-07-01
  8      11511     1 2018-08-01
  9      11511     1 2018-09-01
  10      11511     1 2018-10-01
  # ... with 14 more rows
相关问题