Bookmark and Share

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: Is there a way to replace a variable with a missing value without knowing if it is numeric or string?


From   David Braudt <[email protected]>
To   statalist <[email protected]>
Subject   Re: st: Is there a way to replace a variable with a missing value without knowing if it is numeric or string?
Date   Fri, 26 Jul 2013 03:22:06 -0600

You can also try using the substr command in conjunction with :type to
capture the variable type and then execute string specific commands.
Sample code would be:

foreach var in name age position startdate {
    if substr("`:type `var''",1,3) == "str" {
          replace `x' ="" if female == 1
    }
    else {
          replace `var'=. if female==1
     }
}


In the syntax for the line:  if substr("`:type `var''",1,3) == "str" {
there are two single right quotes followed by a double quote after var.

I hope this helps... but in any case it was fun to figure out.

Cheers,

David Braudt

FHSS Research Support Center
Brigham Young University
fhssrsc.byu.edu

On Fri, Jul 26, 2013 at 2:14 AM, Phil Clayton
<[email protected]> wrote:
> The easiest solution is probably the brute force approach:
>
> foreach var in name age position startdate {
>         capture replace `var' = . if indicator == 1
>         capture replace `var' = "" if indicator == 1
> }
>
> A more elegant solution might use -ds-, -confirm- or the "type" macro extended function (-help extended_fcn-), but the above solution is fast and simple.
>
> Phil
>
> On 26/07/2013, at 5:18 PM, "Gupta, Ani" <[email protected]> wrote:
>
>> I have a series of variables, - say name, age, position, startdate - some of which are numeric and some of which are string. I want to replace their values with missing values if another variable, indicator is equal to 1.
>>
>> In other words I want to be able to write something like this:
>>
>> foreach var in name age position startdate {
>>       replace `var' = _missing_ if indicator == 1
>> }
>>
>> Is there a way I can do this in a single loop for numeric and string variables?
>>
>>
>> *
>> *   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/
*
*   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/


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