Series of Percentage Changes

Discussion in 'Mathematica' started by Gregory Lypny, Feb 25, 2009.

  1. Hello everyone,

    We can transform a series to percentage changes by using

    ([email protected])/([email protected])


    ([email protected]/[email protected]) - 1

    However, Mathematica will smartly difference symbols as well as
    numeric values, so the difference of adjacent null elements will be
    zero (Null - Null = 0), resulting in a percentage change of zero, and
    so will adjacent elements with a string, such as "NA" or "Missing",
    that denotes a missing value. The trouble is, you may want to have
    missing values flagged in the resulting percentage change series just
    as they were in the original series.

    I wrote the following little function, which makes use of a Do loop,
    to take care of missing values and instances of division by zero, but
    I was wondering whether there is a more elegant way to incorporate the
    conditions with functions such as Rest and Most and perhaps avoid the
    use of the loop.

    percentageChange[theList_] := Module[{tmpList, tmpElements},
    (tmpList = Array[tmpElements, ([email protected]) - 1];
    Do[tmpList[[t - 1]] =
    If[theList[[t - 1]] != 0 && NumberQ[theList[[t - 1]]] &&
    NumberQ[theList[[t]]], theList[[t]]/theList[[t - 1]] - 1,
    "NA"], {t,
    2, [email protected]}];


    Gregory Lypny, Feb 25, 2009
    1. Advertisements

  2. Gregory Lypny

    dh Guest

    Hi Gregory,

    you may use MapThread together with a function thta checks its

    arguments. E.g.:

    fun = If[NumericQ[#1] && NumericQ[#2], (#2 - #1)/#1, NA] &;

    MapThread[fun, {Most[theList], Rest[theList]}]

    hope this helps, Daniel

    dh, Feb 26, 2009
    1. Advertisements

  3. Gregory Lypny

    Raffy Guest

    pchg[v_List, h_: "NA"] := [email protected][Check[#1/#2 - 1, h] &, {Rest
    [v], Most[v]}];
    Raffy, Feb 26, 2009
  4. Hi Gregory,

    If[NumericQ[#1] && NumericQ[#2], 100 Subtract[##]/#1, NA] & @@@
    Partition[theList, 2, 1]

    should work for you. You might add a minus sign to the 100 depending
    on which way you want the differences be calculated.

    Cheers -- Sjoerd

    Sjoerd C. de Vries, Feb 26, 2009
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.