Break a command into several lines in do-file in Stata
Asked Answered
M

2

11

I want to run the keep command in a do-file in Stata 12:

keep a1 a2 a3 a4 a5 b1 b2 b3 b4 b5 c1 c2 c3 c4

What I want is to do the following:

keep {a1 a2 a3 a4 a5
     b1 b2 b3 b4 b5
     c1 c2 c3 c4}

I know the {} brackets don't do the trick but I'm looking for the command that does it. Using #delimiter ; does not work either.

I want to do this because subgroups of variables have a relation among themselves (which I intended to signal above by using a, b and c) and I want to have that clear in my code. I permanently add and delete variables. Note that I don't want to use the drop command (in which case the solution is trivial).

Maremma answered 14/8, 2014 at 2:48 Comment(1)
Statements like "the delimiter command doesn't work" are always incorrect, especially when no code or output was shown.Jacobjacoba
C
22

There are several ways. One is using ///. An example:

clear all
set more off

*----- example data -----

set obs 1

forvalues i = 1/25 {
    gen var`i' = `i'
}

describe

*----- what you want -----

keep var1 var2 ///
    var3-var7 ///
    var8 var11

describe

#delimit will work if used correctly. An example:

<snip>

*----- what you want -----

#delimit ;

keep var1 var2 
    var3-var7 
    var8 var11 ;

#delimit cr

describe

There is still another way. help delimit (which you already knew about) states:

See [U] 16.1.3 Long lines in do-files for more information.

That manual entry points you directly to the relevant information.

I suspect lack of research/effort in this case. A Google search (with "stata + break lines in do files") would have easily gotten you there. I'm not recommending this be your first strategy when trying to solve problems in Stata. Rather, start with Stata resources: I recommend reading

[U] 3 Resources for learning and using Stata

[U] 4 Stata’s help and search facilities.

Ceciliacecilio answered 14/8, 2014 at 3:9 Comment(0)
T
2

This is just a very simple trick to complement the real solutions by Roberto. Since you have so many variables, one thing I found sometimes useful is to use macros to group variables, especially if you can use the grouping in more than one occasion.

loca a a1 a2 a3 a4 a5
loca b b1 b2 b3 b4 b5
loca c c1 c2 c3 c4 c5
keep `a' `b' `c'
Tory answered 14/8, 2014 at 6:17 Comment(2)
Using wildcards or variable ranges can be even easier. keep a? b? c? or keep a1-a5 b1-b5 c1-c5 might be enough.Anaheim
That sure makes it better, assuming the variables are named neatly. The OP could end up fitting in all macro names in one line.Tory

© 2022 - 2024 — McMap. All rights reserved.