0

I have two variables message_one and message_two.

While looping over variables, I want to display message_one if "vari" is varone, and display message_two if "vari" is vartwo.

What I want to do is different but this is an example.

I am doing the following and it does not work.

foreach vari in varone vartwo {

local suffix "one" if `vari'==varone
local suffix "two" if `vari'==vartwo

display(message_`suffix')

}

How should I change the local lines to make it work?

That is, I want to add a variable which corresponds to the looping variable for each loop.

1 Answer 1

1

The if condition won't work here. In general, it identifies observations that satisfy some condition. In particular, that makes no sense as qualifying local as there is no implicit loop over observations in assigning contents to a macro. So, the likely consequence of your syntax is an illegal syntax message ("does not work" is never a precise problem report).

However, note that the effect of something like

 local foo if 2 == 2 

is just to copy the text if 2 == 2 into local macro foo.

What you want is perhaps more like

foreach vari in varone vartwo {
       di cond("`vari'" == "varone", "one", "two") 
} 

but that loop is pointless as a single direct statement suffices:

di "one" _n "two" 

You could do this instead:

foreach vari in varone vartwo {
       if "`vari'" == "varone" di "one" 
       else di "two" 
} 

The if command here is quite different from the if qualifier.

I have had to make guesses at what you want here.

First, I added double quotes on the surmise that you want to compare strings directly. If you want something else, please explain.

Second, a statement like

display(message_one) 

would work if and only if message_one were a predefined variable (in which case you would see a display of its value in the first observation) or a predefined scalar. But storing a single text message in a variable is unnecessary, especially if the same text is repeated in every observation, as it would be with something like

  gen foo = "this message" 

In Stata that is not a good way to define a scalar. Just defining a message as a literal text string within a program is almost always simplest and best.

What you asked is evidently a minimal version of your real problem, but equally I don't know what that real problem is.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.