Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


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

Re: st: variable names in matrix


From   Nick Cox <njcoxstata@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: variable names in matrix
Date   Tue, 10 May 2011 08:08:49 +0100

Daniel's good work can be polished slightly. If you want the sum of a
variable in Stata, it is not necessary either to use -sum()- or -egen,
total()-. -summarize- produces the sum; it does not display it, but
that is not a problem. Thus you need not create a new variable, either
way.

Here is Daniel's first example revisited:

/*---example 1A---*/
unab vars : *
mat A = J(`: word count `vars'', 1, .)
mat rownames A = `vars'
loc i 0
foreach v in `vars' {
     su `v', meanonly
     mat A[`++i', 1] = r(sum)
}

Nick

On Mon, May 9, 2011 at 11:53 PM, daniel klein
<klein.daniel.81@googlemail.com> wrote:
> Stefan,
>
> there are several problems with your code. Firstly,
>
> "mat A=J(1,2,.)"
>
> will not work, because in your example your matrix A has 3 rows, not
> only 1. Secondly you do not need 2 colums, because, as you have
> already pointed out, a matrix may not conatin strings. But see -help
> mat rownames- for an alternative.
>
> "scalar aaa=sum(`var')
> mat A=(A \ ??? , aaa)"
>
> will also not do what you probably expect it to do. Firstly -sum()-
> returns the runnig sum of a variable. You are probably looking for
> -total()-, an -egen- function. Secondly, within a loop you want to
> code something like
> . mat A[`i', 1] = x
>
> Please see -help matrix-.
>
> Here are two rather ad hoc solutions:
>
> /*---example 1---*/
> tempvar s
> unab vars : *
> mat A = J(`: word count `vars'', 1, .)
> mat rownames A = `vars'
> loc i 0
> foreach v in `vars' {
>   qui g `s' = sum(`v')
>   mat A[`++i', 1] = `s'[_N]
>   drop `s'
> }
>
> matlist A
> /*---end---*/
>
> /*---example 2---*/
> mata :
>   A = .
>   st_view(A, ., .)
>   st_matrix("A", colsum(A)')
> end
> unab nams : *
> mat rownames A = `nams'
>
> matlist A
> /*---end---*/

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index