Reputation: 6409
I have a large matrix consisting of 116 columns and 4700 rows.
For each row I would like to compute a standardized difference of the following form:
(((a2-a1)/a1)*100)+100, where a1 is the previous value and a2 is the next value.
In R I'm using the following code:
for i in (1:116)
a[i]=(((a[i]-a[i-1])/a[i-1])*100)+100
However I get the following error:
Error in Ops.data.frame(a[i], a[i - 1]) :
- only defined for equally-sized data frames
I'm guessing that the problem is that it does not take into account the very first value, where there does not exist a first value-1 to substract.
How can I solve this problem?
Here's a subset of the data: https://dl.dropbox.com/u/22681355/su.csv
Remember that I would like to calculate for each column individually!
Upvotes: 0
Views: 610
Reputation: 47582
Your question could use a reproducible example to make it clearer. For example, you say you have a matrix but then show an error that is related to data frames. Without knowing what your data looks like we can not know if answers are correct.
But anyway, I think you can do this without loops as follows.
# Example data:
foo <- data.frame(A = 1:10, B = rnorm(10))
# Compute standardized differences:
(foo[-1,] - foo[-nrow(foo),]) / foo[-nrow(foo),] * 100 + 100
Upvotes: 1