0

So I have a 252 rows of data in column 4, and I would like to find the difference between two consecutive rows throughout the entire column

My current code is:

appleClose<-NULL
for (i in 1:Apple[1]){
  appleClose[i] <- AA[i,4]
}
appleClose[] 

I tried, and failed, with:

appleClose<-NULL
for (i in 1:Apple[1]){
  appleClose[i] <- AA[i,4] - AA[i+1,4]
}
appleClose[]

Edit: I am trying to optimize a stock market portfolio in retrospect. AA is the ticker symbol for Apple. I downloaded that information through some R code written earlier in the program. I have not yet checked out the diff function yet. I will do that now.

The error I am receiving is

Error in [.xts(AA, i + 1, 4) : subscript out of bounds

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
AJ19
  • 83
  • 7
  • 2
    What error do you get? What is `Apple` and `AA`? Without much data, it is hard to answer your question. I would look at [this question](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) about making a great reproducible example. – Christopher Louden Feb 07 '14 at 16:52
  • 2
    Have you checked out the `diff` function? – Stephen Henderson Feb 07 '14 at 16:52
  • Yes, please produce a small reproducible example of input and expected output – digEmAll Feb 07 '14 at 16:57
  • 1
    He is probably getting out of bounds in his indexing. – celiomsj Feb 07 '14 at 17:01
  • use diff. or c(NA,x)-c(x,NA). why d'ya get an error? hard to tell from your cryptic notation but if you loop from 1 to length of x then x[i+1] won't exist – lebatsnok Feb 07 '14 at 17:02

2 Answers2

2

Is this what you mean?

> Apple=runif(5,1,10)

#5 numbers
> Apple
[1] 3.362267 2.489085 3.899513 5.591127 9.315716

#4 differences
> diff(Apple)
[1] -0.8731816  1.4104271  1.6916143  3.7245894

or depending on your data either

>diff(AA$Apple)

or maybe

>diff(AA[,4])
Stephen Henderson
  • 6,340
  • 3
  • 27
  • 33
0

Another option (if you are referring to this, your question is not much clear)

AA[-1,4]- AA[-dim(A)[1],4]

Rufo
  • 524
  • 1
  • 3
  • 18