Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
RE: st: Making a matrix out of three variables
From
Eilya Torshizian <[email protected]>
To
"'[email protected]'" <[email protected]>
Subject
RE: st: Making a matrix out of three variables
Date
Thu, 16 Jan 2014 21:50:11 +0000
Hi Cohen and Phil,
Thanks for your help. You are right, all the variables are numeric.
Both codes are working well.
Kind regards,
Eilya.
-----Original Message-----
From: [email protected] [mailto:[email protected]] On Behalf Of Phil Schumm
Sent: Friday, 17 January 2014 10:19 a.m.
To: Statalist Statalist
Subject: Re: st: Making a matrix out of three variables
On Jan 16, 2014, at 2:03 PM, Eilya Torshizian <[email protected]> wrote:
> I need to convert three variables to a matrix. The values of variable A and B should be used as row and column names of the output matrix. Let's assume three columns of data, where A, B and C are the name of my numeric variables,
>
> A B C
> A1 | A1 | C1
> A1 | A2 | C2
> A1 | A4 | C3
> A1 | A5 | C4
> A2 | A2 | C5
> A2 | A1 | C6
> A2 | A3 | C7
>
> I need to convert these to the following matrix,
>
> A1 A2 A3 A4 A5
> A1 C1 C2 0 C3 0
> A2 C6 C5 C7 0 0
>
> As I have a wide range of observations, I would like to avoid nested loops.
Assuming C is a numeric variable, the following will do what you want (with the resulting matrix named "M"):
reshape wide C, i(A) j(B) string
mkmat C*, matrix("M") rownames(A)
mata: st_matrix("M", editmissing(st_matrix("M"),0))
Note that the only way to replace the initial missing values of the matrix with 0s is to use the Mata function editmissing().
-- Phil
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/faqs/resources/statalist-faq/
* http://www.ats.ucla.edu/stat/stata/