s-news
[Top] [All Lists]

Re: calculate many differences w/o forloop?

To: "Johnnidis, Jonathan" <Jonathan.Johnnidis@joslin.harvard.edu>, <s-news@lists.biostat.wustl.edu>
Subject: Re: calculate many differences w/o forloop?
From: "Johnnidis, Jonathan" <Jonathan.Johnnidis@joslin.harvard.edu>
Date: Mon, 26 Apr 2004 12:06:30 -0400
Thread-index: AcQrpnhTgW+CGQOfRaKET6tRb0qdxwAAdDtp
Thread-topic: calculate many differences w/o forloop?
dear all: many thanks for your extremely rapid and thoughtful responses.
it appears the way to go is with the diff() function.
jonathan

        -----Original Message----- 
        From: Johnnidis, Jonathan 
        Sent: Mon 4/26/2004 11:52 AM 
        To: s-news@lists.biostat.wustl.edu 
        Cc: 
        Subject: [S] calculate many differences w/o forloop?
        
        

        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]
        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.
        
        with thanks,
        Jonathan
        
        --------------------------------------------------------------------
        This message was distributed by s-news@lists.biostat.wustl.edu.  To
        unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
        the BODY of the message:  unsubscribe s-news
        

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