一种选择是使用uncount
重复行 12 次,创建一个新列month
来1:12
为每个列取值year
,然后将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
或者另一个选项complete
和fill
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)