Katsuhide Isa wrote:
> I have two questions about matrix operations in Stata.
> Suppose there is a matrix form data set like below:
>
> A B C D
> A 0 0 0 1
> B 0.3 0 0 0.7
> C 0.2 0.15 0.65 0
> D 0.3 0.4 0 0.3
>
> Question 1.
> To compute sum of numbers of zeros for this matrix, I wrote
> the following:
>
> foreach var of varlist A-D{
> count if `var' == 0
> }
>
> The result is:
>
> 1
> 2
> 3
> 1
>
> Namely, numbers of zeros for each variable are vertically
> shown.
> One step further, I'd like to obtain total sum of numbers
> of zeros (1+2+3+1=7 in this case).
> Is it possible to do so?
In Stata, the term matrix is used for objects accessible with the various
subcommands of the command -matrix-. Therefore, strictly speaking, you do not
have a matrix, but a dataset. However, the answer to your question is "yes".
There are many ways to do it. Here is one to start with:
foreach var of varlist A-D{
count if `var' == 0
local sum = `sum' + r(N)
}
di `sum'
> Question 2.
> To compute sum of row variances, I wrote the following:
>
> /* sum of row variances */
> loc egen sd = rsd(A-D)
> loc egen v = sd^2
> loc egen sumv = sum(v)
> di in gr " sum of row variances" _col(38) ": " %5.3f in ye `sumv'
>
> While no errors are shown, the result for `sumv' are not
> shown, either.
> # Only the title "sum of row variances : " is shown.
>
> I don't know why this happens, thoguh I may have made some
> elementary mistakes.
You have used "local" in front of your -egen- commands. I am not sure why you
did this. However what in effect you did is to store all the egen commands in
local macros. Try out
. local egen sumv = sum(v)
. display "`egen'"
to see what happened.
> Is there any alternatives to compute?
. egen sd = rsd(A-D)
. gen sumv = sum(sd^2)
. di sumv[_N]
--
[email protected]
+49 (030) 25491-361
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/