s-news
[Top] [All Lists]

Re: calculate many differences w/o forloop?

To: "Johnnidis, Jonathan" <Jonathan.Johnnidis@joslin.harvard.edu>
Subject: Re: calculate many differences w/o forloop?
From: Sundar Dorai-Raj <sundar.dorai-raj@PDF.COM>
Date: Mon, 26 Apr 2004 11:13:08 -0500
Cc: s-news@lists.biostat.wustl.edu
In-reply-to: <5B090EB78E8ADD4E9DFBD45E2240C2C2F09060@MAIL2.joslin.harvard.edu>
Organization: PDF Solutions, Inc.
References: <5B090EB78E8ADD4E9DFBD45E2240C2C2F09060@MAIL2.joslin.harvard.edu>
Reply-to: sundar.dorai-raj@PDF.COM
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)


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


<Prev in Thread] Current Thread [Next in Thread>