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: Regular expressions with locals
From
Nick Cox <[email protected]>
To
[email protected]
Subject
Re: st: Regular expressions with locals
Date
Tue, 26 Jun 2012 16:14:23 +0100
Tirthankar answered this one yesterday before my posting. His code can
be adapted to this question.
Here's another solution for two underscores. (For the last underscore
of three or more, reverse the string and look for the first.)
clear
set obs 3
gen phstat = _n
forval i = 1/3 {
gen _Iphstat_`i' = phstat == `i'
}
* transformation
foreach v of var _Iphstat* {
local out = substr("`v'", strpos("`v'", "_") + 1, .)
local out = substr("`out'", 1, strpos("`out'", "_") - 1)
di "`out'"
}
Nick
On Tue, Jun 26, 2012 at 4:01 PM, Anthony Hong <[email protected]> wrote:
> Hey Nick, that's similar to what I am doing now, but I figured,
> because I've never used regular expressions before, it would be an
> opportunity to try it out.
>
> Also, you guessed right. That I'm trying to grab labels and make a table.
>
> Would you know how I could do this with regular expressions though?
>
> Because suppose the variable has an underscore in between it? I would
> like to be able to identify the portion between the first and last
> underscore only and grab the text in between.
>
>
>
> On Tue, Jun 26, 2012 at 4:48 AM, Nick Cox <[email protected]> wrote:
>> For the record, I give an orthodox non-regular expression solution.
>> This example guesses that (a) Anthony wants to emit the output one
>> variable at a time (b) he wants variable labels. Either guess could be
>> wrong, naturally.
>>
>> * sandpit to play in
>>
>> set obs 3
>> gen phstat = _n
>> forval i = 1/3 {
>> gen _Iphstat_`i' = phstat == `i'
>> }
>>
>> * transformation
>>
>> forval i = 1/3 {
>> local in _Iphstat_`i'
>> local out : subinstr local in "_I" ""
>> local out : subinstr local out "_" " = "
>> label var `in' "`out'"
>> }
>>
>>
>> On Tue, Jun 26, 2012 at 5:33 AM, Anthony Hong <[email protected]> wrote:
>>
>>> Hello! I have in a local macro a list of variables such as _Iphstat_1
>>> from xi: logistic. I would like to remove the _I from the beginning
>>> and the _# from the end and create a new local with simply a string
>>> "phstat = 1".
>>>
>>> How might I go about doing this?
>>>
>>> I realize this can be done with various string functions, but I'm
>>> curious about the regex commands.
*
* 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/