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: How to apply a command to numeric variables only


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: How to apply a command to numeric variables only
Date   Tue, 29 May 2012 08:27:33 +0100

Similar questions arise often on this list. In your case one solution
is to -destring- the string variables before the loop, but then the
loop will convert back, so that does not appeal.

Another is to select numeric variables beforehand. -ds- will do this

ds srhcareactivity1-srhcareactivity6 , has(type numeric)

foreach var in `r(varlist)' {

-findname- (SJ) can do more than -ds- (fact) and has a better syntax
(opinion), but its use is very similar here.

findname srhcareactivity1-srhcareactivity6 , type(numeric)

foreach var in `r(varlist)' {

Another way is to use -capture- inside the loop.

 foreach var of varlist srhcareactivity1-srhcareactivity6{
     capture decode `var', generate(string)
     if _rc == 0 {
             drop `var'
             rename string `var'
      }
}

Is it "string" a reserved word? (I am away from manuals at the
moment.) I'd use something different here, even if not.

Keeping the variable label can be done with extended macro functions,
mentioned frequently on this list.

 foreach var of varlist srhcareactivity1-srhcareactivity6{
     local varlabel : variable label `var'
     capture decode `var', generate(string)
     if _rc == 0 {
             drop `var'
             rename string `var'
             label var `var `varlabel'
      }
}

See -help extended fcn-. Or -help macro- first.

Nick

On Tue, May 29, 2012 at 6:28 AM, Paul O'Brien <[email protected]> wrote:
> I want to do a foreach command to convert numeric variables to string before a merge. Only some of the variables are numeric and which ones varies with each database.
>
> foreach var of varlist srhcareactivity1-srhcareactivity6{
>        decode `var', generate(string)
>        drop `var'
>        rename string `var'
> }
>
> Error message: not possible with string variable.
>
> I have tried using capture to ignore the error.
>
> How can I restrict the command to numeric variables only?
>
> By the way, is there a way to keep the variable label which is lost when I use generate.
>

*
*   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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index