R函数用于每月扩展表,给定开始月和结束月

时间:2019-04-27 04:35:30

标签: r dplyr

我在R中有一个数据集,该数据集与价格的有效开始和结束月份(持续时间)有关。下面是一个示例:

print(df)

    Customer Product Price Start_Month End_Month
    ABC      XYZ     100   Jan         Jun
    ABC      XYZ     150   Jul         Dec

我需要编写可以每月花费此表的代码/功能。我的预期结果如下:

Customer Product Price Month
ABC      XYZ     100   Jan
ABC      XYZ     100   Feb
ABC      XYZ     100   Mar
ABC      XYZ     100   Apr
ABC      XYZ     100   May
ABC      XYZ     100   Jun
ABC      XYZ     150   Jul
ABC      XYZ     150   Aug
ABC      XYZ     150   Sep
ABC      XYZ     150   Oct
ABC      XYZ     150   Nov
ABC      XYZ     150   Dec

我找不到其他类似的问题可以帮助我解决问题。

2 个答案:

答案 0 :(得分:2)

一种match方法是将数据帧转换为长格式,这样我们现在原始数据帧中的每一行都有两行。现在,对于每一行,我们使用library(tidyverse) df %>% gather(key, Month, -(1:3)) %>% group_by_at(1:3) %>% complete(Month = month.abb[match(Month[1], month.abb): match(Month[2], month.abb)]) %>% arrange(Customer, Product, Price, match(Month, month.abb)) %>% select(-key) # Customer Product Price Month # <fct> <fct> <int> <chr> # 1 ABC XYZ 100 Jan # 2 ABC XYZ 100 Feb # 3 ABC XYZ 100 Mar # 4 ABC XYZ 100 Apr # 5 ABC XYZ 100 May # 6 ABC XYZ 100 Jun # 7 ABC XYZ 150 Jul # 8 ABC XYZ 150 Aug # 9 ABC XYZ 150 Sep #10 ABC XYZ 150 Oct #11 ABC XYZ 150 Nov #12 ABC XYZ 150 Dec 获取开始和结束月份中月份值的索引,然后使用该值创建一个序列。

map2

或使用df %>% mutate(Month = map2(Start_Month, End_Month, ~month.abb[match(.x, month.abb) : match(.y, month.abb)])) %>% unnest() %>% select(-Start_Month, -End_Month)

的另一个选项
Map

在基数R中将使用do.call(rbind, Map(function(x, y, z) cbind(df[z,], Month = month.abb[match(x, month.abb) : match(y, month.abb)]), df$Start_Month, df$End_Month, seq_len(nrow(df))))

month.abb

在这里,我们利用内置的month.abb # [1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" 向量获得序列

{{1}}

答案 1 :(得分:1)

使用基数r:

do.call(rbind,lapply(1:nrow(df), 
                             function(x) {
                                      cbind(df[x], 
                                      data.frame(Months=
                                                month.abb[which(month.abb==df[x]$Start_Month):
                                                          which(month.abb==df[x]$End_Month)]))
                                }))