为多个变量申请或循环

时间:2018-10-26 04:41:30

标签: r for-loop

我有两个要应用于代码的日期列表(第一个日期在xx中,第一个日期在yy中,第二个日期在xx中,第二个日期在yy中,等等)。 (示例中有简短的日期列表)。 trade1是空的,所以我正在解决这个错误。

xx= c('2018-06-28','2018-07-27')
yy= c('2018-07-12','2018-08-13')

for (xx in seq_along(yy)) 
{
entry_trades = filter(aa2, Date == xx )%>%
          rename(entry_price = Price, entry_date = Date)
exit_trades = filter(aa2, Date == yy)%>%
         rename(exit_price = Price, exit_date = Date)
trade1 = merge(entry_trades, exit_trades,by='ticker')
trade1 = mutate(trade1, Chg = exit_price - entry_price,
            Chg_pct = round((Chg / entry_price)*100 ,1))%>%
arrange(desc(Chg_pct))
}

1 个答案:

答案 0 :(得分:0)

for (i in seq_along(yy)) 
{
entry_trades = filter(aa2, Date == xx[i] )%>%
          rename(entry_price = Price, entry_date = Date)
exit_trades = filter(aa2, Date == yy[i])%>%
         rename(exit_price = Price, exit_date = Date)
trade1 = merge(entry_trades, exit_trades,by='ticker')
trade1 = mutate(trade1, Chg = exit_price - entry_price,
            Chg_pct = round((Chg / entry_price)*100 ,1))%>%
arrange(desc(Chg_pct))
}

可能有更好的方法来做您想做的事情,但是我不确定那是什么,并且您没有给我们aa2,所以很难弄清楚< / p>