Search code examples
sqlvisual-foxprofoxpro

Multiply and subtract values in previous row for new row in FoxPro


I'm trying to write command in fox pro that helps me calculate two variables in a table that looks like this

age   death_rate   alive   dead
1      0.003       1000     3
2      0.001       997      1
3      0.0006
4      0.005
5      0.002
...

alive at age x = (alive at age x-1) - (dead at age x-1)

dead at age x = (death_rate at age x) * (alive at age x)

I'm trying to calculate rest of the values for alive and dead automatically but the two empty columns are dependent on each other in calculation, I'm not sure how the command should look like


Solution

  • I cannot give you one command to do this, but it is relatively easy if you use a small program. I don't know what data file type you are using (VFP table, MSSQL table) so I will demonstrate with a VFP cursor. You can open a new program window in VFP by typing MODIFY COMMAND in the command window. Paste the following code in the Program window, highlight the code, right-click and Execute Selection.

    CREATE CURSOR deathrate (age i,death_rate n(6,4),alive i, dead i)
    INSERT INTO deathrate (age,death_rate,alive,dead) VALUES (1,.003,1000,3)
    INSERT INTO deathrate (age,death_rate,alive,dead) VALUES (2,.001,997,1)
    INSERT INTO deathrate (age,death_rate,alive,dead) VALUES (3,.0006,0,0)
    INSERT INTO deathrate (age,death_rate,alive,dead) VALUES (4,.005,0,0)
    INSERT INTO deathrate (age,death_rate,alive,dead) VALUES (5,.002,0,0)
    GOTO 2 && you have supplied the first 2 values, go to record 2
    SCATTER NAME oprev  && create a scattered object of the current record, then...
    SKIP    && skip 1 record
    SCAN rest
        replace alive WITH oprev.alive - oprev.dead, dead WITH round(death_rate * alive,0)
        SCATTER NAME oprev    && refresh before skipping to next record
    ENDSCAN
    BROWSE NORMAL LAST
    

    The result is:

          AGE DEATH_RATE       ALIVE        DEAD
            1     0.0030        1000           3
            2     0.0010         997           1
            3     0.0006         996           1
            4     0.0050         995           5
            5     0.0020         990           2