Jolien .A - 8 months ago 50

R Question

I try to subtract two vectors with each length 7 from another. Yet my results won't produce another vector, I simply get numeric 0 and data 0. Any idea?

`#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)

Answer

I have copied your vectors from clipboard. What I did to achieve what you want:

```
# 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.
```

Do the same with the second vector and subtract

```
SLB_sell-SLB_buy
```

Source (Stackoverflow)