Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: st: New variable based on a sum of products of another variable

From   Nick Cox <>
To   "''" <>
Subject   RE: st: New variable based on a sum of products of another variable
Date   Wed, 25 May 2011 15:55:30 +0100

Thanks for the update. At some point, it becomes natural to learn Mata for stuff like this. As they say, the learning curve is steep, meaning put in a little effort and you learn a lot. 


Seamer Paul

Many thanks to Nick and Paul for their suggestions,

Apologies that it’s taken me a while to reply.

Paul’s iterative solution is a neat answer to the question I posed, but there was an additional step that I didn’t mention in my original post,

I need to multiply each of the product terms (in parentheses in my original post) by another 2 variables before I perform the summation,

Essentially I’m looking generate a probability (P) that is of the form,

(P)= ∑ {var1} {var2} { ∏ var3 }

My original post related to calculating the sum product of var3, but I need to do this for different values of each variable and then perform a summation for each time period.

Nick's hint led me to a solution using logarithms ? it has a number of steps, but gives the answer I was looking for,
The values x are chronological years and i values are age in years (I'm using the probabilities to populate an illness-death Markov-type model).

.forvalues x = 1903/1997 {
.forvalues i = 1/41 {
.gen p`x'`i' = exp(sum(ln(var3`x')) - sum(ln(var3`x'[_n-`i']))) * var2`x'[_n-(`i'-1)]
.replace p`x'`i' = p`x'`i' * var1`x'[_n-`i'] if _n>=`i'+1
.forvalues j = 2/41 {
.replace p`x'1 = p`x'1 + p`x'`j' if _n>=`j'
.drop p`x'2-p`x'41 
.rename p`x'1 p`x' 

*   For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index