Johnnidis, Jonathan wrote:
dear list:
I have a matrix which contains a column of 10000 numbers, and would like to
calculate the difference between each number and the number that follows it
(for a total of 999 calculated differences), and dump that calculation into a
newly-created second column.
In Excel I could simply write a formula in cell B2: =A2-A1, and then fill
column B downwards with that formula, and the result would be calculated nearly
instantaneously.
However in S I'm not quite sure how to do this, and have been using a for-loop:
----------------------------------
for (i in 1:(nrow(matrix)-1)) #the '-1' is so it doesn't perform the
calculation for last number
{
diff <- matrix[i+1,1] - inputmatrix[i,1]
this line should be `inputmatrix[i+1,1] - inputmatrix[i,1]', right??
matrix[i,"diff"] <- diff
}
----------------------------------
This does the job but apparently is extremely processor intensive, and takes a
Long Time. Is there a faster/better way to do this (perhaps that take
advantage of the vector capabilities of S+/R)??
I'd much appreciate any ideas or suggestions.
I think you're looking for ?diff:
mat <- matrix(rnorm(10000), 10000, 1)
mat <- cbind(input = mat[, 1], diff = c(NA, diff(mat[, 1])))
The NA in the first row means the second row is where the differences begin.
Note, you should avoid using names like `matrix' and `diff' as they are
S-PLUS functions. Most of the time S-PLUS can tell the difference by
context, but not always.
--sundar
|