Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
From | Nick Cox <njcoxstata@gmail.com> |
To | "statalist@hsphsun2.harvard.edu" <statalist@hsphsun2.harvard.edu> |
Subject | Re: st: Re: How to determine if a variable is a dummy in mata |
Date | Sun, 17 Nov 2013 11:01:29 +0000 |
(2) better as : all((x :== 0) :| (x :== 1)) Nick njcoxstata@gmail.com On 17 November 2013 10:09, Nick Cox <njcoxstata@gmail.com> wrote: > Here are some other solutions. > > (1) > > Only for 0 and 1 is a number equal to its own square. Hence > > : x = (0,0,0,0,1,1,1) > > : x == x:^2 > 1 > > A graph such as > > twoway function x^2, ra(-3 3) || function x, ra(-3 3) > > may help make this vivid. > > (2) > > sum((x :== 0) :| (x :== 1)) == length(x) > > Nick > njcoxstata@gmail.com > > On 17 November 2013 05:30, Joseph Coveney <stajc2@gmail.com> wrote: >> Paul Corral wrote: >> >> I'm been trying to determine if a variable is a dummy or not within mata. >> >> Is there an easy way to do this without iterating over each row of a >> matrix's column and check if it is either 0 or 1. I was trying to use >> the allof() command, however it can only check if all are a scalar. >> So, while I may check if all are ones, it won't allow me to check if >> all are 0 or 1. >> >> -------------------------------------------------------------------------------- >> >> Something like that below should work. If you don't like the verbosity, you can >> condense it all to a single line of code, although it might make it difficult to >> follow. >> >> Other ways come to mind to accomplish the same thing, for example, to covert the >> column to text and then use a string search (glance through Mata's string >> functions for guidance) for characters other than "0" and "1". Some of them >> might be more efficient, too. >> >> Joseph Coveney >> >> : mata set matastrict on >> >> : >> : real scalar function indicator( >>> real matrix TestedMatrix, >>> real scalar tested_column_index) { >>> >>> real colvector TestedColumn >>> TestedColumn = TestedMatrix[., tested_column_index] >>> >>> TestedColumn = uniqrows(TestedColumn) >>> >>> real scalar result >>> result = ( >>> (TestedColumn[1] == 0) && >>> (TestedColumn[2] == 1) && >>> (rows(TestedColumn) == 2) >>> ) >>> >>> return(result) >>> } >> >> : >> : A = (0, 1, 2, 3 \ 1, 4, 5, 6 \ 0, 7, 8, 9) >> >> : >> : indicator(A, 1) >> 1 >> >> : indicator(A, 2) >> 0 >> >> : >> : A = A \ (10, 11, 12, 13) >> >> : >> : indicator(A, 1) >> 0 >> >> : >> : end * * 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/