在年度数据中插入对应于每个月的行

Insert rows corresponding to each month in an yearly data

我有一个包含 2014 年至 2018 年年度数据的数据框。我希望将此数据框扩展为月度值,并且基本上将每个变量的值除以 12 作为每个月的值。 请注意:到目前为止,我的数据框中没有月份列。 所以,如果有 5 个产品,我有 5*5 行和 5 列:"year"、"Product_ID"、"Var1"、"Var2" 和 "Var3" 作为列.

最终,我想要插入 5*12 行和 6 列 "month"。

我试过这段代码,但它不起作用:

df_new$date <- NA
df_new <- complete(df,Product_ID, date = full_seq(2014,1))

有什么建议吗?

一个选项是使用 uncount 重复行 12 次,创建一个新列 month 为每个 year1:12 值,然后除以 Var 列乘以 12.

library(dplyr)
library(tidyr)

df %>%
  uncount(12) %>%
  group_by(year) %>%
  mutate(month = 1:12) %>%
  mutate_at(vars(Var1, Var2), ~./12)

# Groups:   year [3]
#    year Product_ID  Var1  Var2 month
#   <int> <chr>      <dbl> <dbl> <int>
# 1  2013 A          0.833     5     1
# 2  2013 A          0.833     5     2
# 3  2013 A          0.833     5     3
# 4  2013 A          0.833     5     4
# 5  2013 A          0.833     5     5
# 6  2013 A          0.833     5     6
# 7  2013 A          0.833     5     7
# 8  2013 A          0.833     5     8
# 9  2013 A          0.833     5     9
#10  2013 A          0.833     5    10
# … with 26 more rows

completefill

的另一个选项
df %>%
  mutate(month = 1) %>%
  complete(year, month = 1:12) %>%
  fill(Product_ID, Var1, Var2) %>%
  mutate_at(vars(Var1, Var2), ~./12)

数据

df <- data.frame(year = 2013:2015, Product_ID = c("A", "B", "C"), 
      Var1 = c(10, 20, 30), Var2 = c(60, 80, 120), stringsAsFactors = FALSE)