2015-11-06 59 views
0

我嘗試從每個長度減去另一個長度爲7的兩個向量。然而,我的結果不會產生另一個向量,我只是得到數字0和數據0.任何想法?R減去向量 - 數字0答案

#You will buy these stocks on rows/days 7, 8, 9, 15, 26, 33 and 53. (1 day after days apple dropped more than 2%) 
#Assign the prices of the stocks on these days to a vector 
SLB_buy = c(SLB_close[7],SLB_close[8],SLB_close[9],SLB_close[15],SLB_close[26],SLB_close[34],SLB_close[53]) 
SLB_buy 
      SLB.Close 
2015-08-21  77.50 
2015-08-24  73.87 
2015-08-25  72.52 
2015-09-02  75.41 
2015-09-18  72.54 
2015-09-30  68.97 
2015-10-27  76.95 

#You will sell these stocks on rows/days 10, 11, 12, 18, 29, 36 and 56. (3 day after purchase) 
#Assign the prices of the stocks on these days to a vector 
SLB_sell =c(SLB_close[10],SLB_close[11],SLB_close[12],SLB_close[18],SLB_close[29],SLB_close[36],SLB_close[56]) 
SLB_sell 
     SLB.Close 
2015-08-26  70.09 
2015-08-27  73.85 
2015-08-28  76.06 
2015-09-08  75.54 
2015-09-23  71.94 
2015-10-02  70.32 
2015-10-30  78.16 

#Your profit is equal to the sales price - buy price. Hence substract the previous vectors from each other. 
SLB_sell - SLB_buy 
Data: 
numeric(0) 

Index: 
numeric(0) 
+2

能否請您編輯您的問題向我們展示了dput的'(SLB_sell)'結果和'dput(SLB_buy)'? –

+1

另外,你可能想要做一些像'SLB_Buy = SLB_Close [c(7,8,9,15,26,34,53)]',所以你不必每次都想重新輸入'SLB_Close'一個新的條目。但是,確切的代碼取決於「SLB_Close」的對象類型。 –

+1

這看起來像一個xts或動物園對象。你應該發佈'dput(SLB_buy)'和'dput(SLB_sell)',因爲R對象的打印表示對於它們的實際結構常常是不明確的。 –

回答

1

我已經從剪貼板複製了您的載體。我所做的,以達到你想要的東西:

# remove SLB.Close, which is the first element of the vector. 
#It might not be the case for your actual vector though. 
SLB_buy<-SLB_buy[-1] 
# remove the dates and transform in numeric 

SLB_buy<-substring(SLB_buy, 11) 
SLB_buy<-as.numeric(SLB_buy) 

# depending on your actual vector the position to start substring 
#(in this case 11) might vary. 

做同樣的與第二向量和減去

SLB_sell-SLB_buy 
+0

Whatswithyourbracketsonthefirstline? – Gregor

+0

@Gregor,謝謝,編輯 – Vasile