使用多个数据框过滤数据框值

时间:2019-07-22 18:44:35

标签: r

是否可以在R中执行此操作?有人可以指导我怎么做

对于每个Item-LC组合,我都需要根据x个月的值从df2中过滤出相应的值。

df1

     Item    LC   Fiscal.Month  fcst
1   0S1576  MW92    2019-M06    22
2   0S1576  MW92    2019-M06        18
3   0S1576  RM11    2019-M06    12
4   0S1576  MW92    2019-M07    10
5   0S1576  RM11    2019-M07    10
6   0S1576  MW92    2019-M08    12
7   0S1576  MW92    2019-M09    10

df2

     Item    LC  xmonths
1   0S1576  MW92    3
2   0S1576  RM11    1

df3

Currentmonth
2019-M06

假设0S1576 MW92我有xmonths = 3,那么从Curretmonth 2019-M06应该选择3行作为df1的输出,而对于RM11我们需要1行:

输出:

     Item    LC   Fiscal.Month  fcst
1   0S1576  MW92    2019-M06    22
2   0S1576  MW92    2019-M06        18
3   0S1576  RM11    2019-M06    12
4   0S1576  MW92    2019-M07    10
5   0S1576  MW92    2019-M08    12

1 个答案:

答案 0 :(得分:1)

require(dplyr)
require(lubridate)



df1 <- read.table(text = 
  ' Item    LC   Fiscal.Month  fcst
1   0S1576  MW92    2019-M06    22
2   0S1576  MW92    2019-M06        18
3   0S1576  RM11    2019-M06    12
4   0S1576  MW92    2019-M07    10
5   0S1576  RM11    2019-M07    10
6   0S1576  MW92    2019-M08    12
7   0S1576  MW92    2019-M09    10') 



df2 <- 
  read.table(text = 'Item    LC  xmonths
1   0S1576  MW92    3
2   0S1576  RM11    1')





df3 <- read.table(text = 
                    'Currentmonth
2019-M06', header  = TRUE)




  df1 %>%  
    mutate(Currentmonth = df3$Currentmonth) %>%   ## adding current month 
    left_join(df2)  %>%   
    mutate(Fiscal.Month2 = gsub('M','', Fiscal.Month), 
           Currentmonth2 = gsub('M','', Currentmonth)) %>%  
    mutate(Fiscal.Month2  = paste(Fiscal.Month2, '-15', sep = ''), 
           Currentmonth2 = paste(Currentmonth2, '-15', sep = '')) %>% 
    mutate(Currentmonth2 = as.Date(Currentmonth2), 
           Fiscal.Month2 = as.Date(Fiscal.Month2)) %>% 
    mutate(max_month = Currentmonth2 %m+% months(3)) %>%  
    filter(Fiscal.Month2 <= max_month) %>% 
    select(Item, LC, Fiscal.Month, fcst)  


  # Item   LC Fiscal.Month fcst
  # 1 0S1576 MW92     2019-M06   22
  # 2 0S1576 MW92     2019-M06   18
  # 3 0S1576 RM11     2019-M06   12
  # 4 0S1576 MW92     2019-M07   10
  # 5 0S1576 RM11     2019-M07   10
  # 6 0S1576 MW92     2019-M08   12
  # 7 0S1576 MW92     2019-M09   10
  #   
相关问题