I’ve a very unusual solution to the problem below. I wonder is there a better way to approach this?
The problem: There are 2 data sets stored in two different data frames. 1 of them is a daily balance of product a , while the other is a weekly balance of product b. Due to a request, i need to perform a “union” on the two data frames in order to do a time series visualization. Since product b does not have daily data, the balance will be hold static until the next update.
How do i “expand” table of product b to have the same length as product a table while holding the balance static for days which product b does not have the data?
Table of product A
Data frame name: TableA
Date (yyyy-mm-dd) / Ccy/ Product /Balance
2019-12-01 / USD / A / 100
2019-12-01 / GBP / A / 100
2019-12-02 / USD / A / 200
2019-12-02 / GBP / A / 150
2019-12-03 / USD / A / 180
2019-12-03 / GBO / A / 210
Table of product B
Data frame name: TableB
Date (yyyy-mm-dd) / Ccy/ Product /Balance
2019-12-01 / USD / B / 100
2019-12-01 / SGD / B / 100
2019-12-03 / USD / B / 180
2019-12-03 / SGD / B / 210
My quirky solution below. Do let me know your thoughts and critique. THANK YOU in advance!!
library(tidyverse)
unique_dates <- unique(tableA$date)
expanded_tableB <- unique_dates%>%left_join(tableB, by=c(Date=Date))%>% fill(-c(“date”))%>% fill(-c(“date”),.direction=c(“up”))
union_table <- bind_rows(tableA,expanded_tableB)