我有投资组合,请参阅以下示例:
portfolio <- data.frame(ISIN = c('ABC US Equity', 'DEF US Equity', 'GHI US Equity'),
Buy.Date = c('22.10.2014', '02.05.2015', '07.08.2016'),
Sale.Date = c('30.05.2015', '15.02.2016', '31.12.2017'),
Buy.Price = c('107.1','101.3','97.8'),
Sale.Price = c('85.69', '102.5', '100'),
Position = c('200','250','300'))
> portfolio
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
ABC US Equity 22.10.2014 30.05.2015 107.1 85.69 200
DEF US Equity 02.05.2015 15.02.2016 101.3 102.5 250
GHI US Equity 07.08.2016 31.12.2017 97.8 100 300
我的目标是获取以下视图的单个data.frame:
> portfolio
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
ABC US Equity 22.10.2014 30.05.2015 107.1 85.69 200
ABC US Equity 02.05.2015 30.05.2015 107.1 85.69 200
DEF US Equity 02.05.2015 15.02.2016 101.3 102.5 250
DEF US Equity 30.05.2015 15.02.2016 101.3 102.5 250
DEF US Equity 07.08.2016 15.02.2016 101.3 102.5 250
GHI US Equity 07.08.2016 31.12.2017 97.8 100 300
GHI US Equity 15.02.2016 31.12.2017 97.8 100 300
即,它应该是单个买入和卖出日期的投资组合持有的快照,即实际上它需要将以下数据框合并在一起:
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
ABC US Equity 22.10.2014 30.05.2015 107.1 85.69 200
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
ABC US Equity 02.05.2015 30.05.2015 107.1 85.69 200
DEF US Equity 02.05.2015 15.02.2016 101.3 102.5 250
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
DEF US Equity 30.05.2015 15.02.2016 101.3 102.5 250
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
DEF US Equity 07.08.2016 15.02.2016 101.3 102.5 250
GHI US Equity 07.08.2016 31.12.2017 97.8 100 300
ISIN Buy.Date Sale.Date Buy.Price Sale.Price Position
GHI US Equity 15.02.2016 31.12.2017 97.8 100 300
现在我刚刚提出了两个循环周期,为我创建了每个买入和卖出日期的单个数据框
for(i in unique(portfolio$Buy.Date)) {
nam <- paste("portfolio", i, sep = ".")
assign(nam, portfolio[portfolio$Buy.Date==i,])
}
for(j in unique(portfolio$Sale.Date)) {
nam <- paste("portfolio", j, sep = ".")
assign(nam, portfolio[portfolio$Buy.Date==i,])
}
因此,现在的问题是以某种方式合并所有这些数据帧,以便它将在不同的时间点正确地表示投资组合快照,如上所述。 R能为我提供这项任务的解决方案吗?
请感谢您的所有帮助,谢谢!
P.S。我的投资组合中目前有一些尚未售出的股票,这就是为什么我的销售日期= 31.12.2017。因此,最后一行应指明日期。
答案 0 :(得分:0)
rbind应该有效,确保所有单独的data.frames具有相同的列标题
df1<-data.frame(x=rep(1,5),y=rep(0.5))
df2<-data.frame(x=rep("A",5),y=rep("B",5))
rbind(df1,df2)