Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Creating a new string scalar variable by appending to it

    Hi,

    I have a list of city names stored in a local macro. I want to create a string that looks like cityname1_cityname2_cityname3 (for 3 names) and store it as a new variable so I can call it it to the global defining my directory from where I get the data.

    So as an example, if I have 3 cities defined as "nyc", "manila", "bogota", I have a directory which looks like "$(local_path)/nyc_manila_paris/nyc_manila_paris.csv". Now this city string is arbitrary based on whatever city names I use. So I want to generate a variable "nyc_manila_paris" that I can then reference to create the path variable. How do I do this? I have written some preliminary code below but it does not seem to be working. I have also put the python code below that I would write to create this variable.

    Code:
    *Stata
    scalar citystring = ""
    local cityname "nyc" "manila" "paris" "bogota"
    foreach v of local cityname{
        replace citystring = citystring + "_" + `"`v'"'
    }
    
    global datadir "${local_path}/<reference to scalar variable citystring>/<reference to scalar variable citystring>.csv"
    Code:
    #Python code that I want to replicate in Stata
    
    cityname = ["nyc", "manila", "paris"]
    citystring = cityname[0]
    for c in cityname[1:]:
         citystring = citystring + "_" + c
    
    local_path = "<insert string for local dir>"
    path = local_path+citystring+"/"
    Last edited by Shreya Dutt; 06 Jul 2022, 19:00.

  • #2
    Perhaps this will start you on a more effective path, rather than trying to translate Python code into very un-Stata-like Stata code.
    Code:
    . global local_path /whatever 
    
    . local cityname "nyc manila paris bogota"
    
    . local citystring : subinstr local cityname " " "_", all
    
    . global datadir "${local_path}/`citystring'/`citystring'.csv"
    
    . display "${datadir}"
    /whatever/nyc_manila_paris_bogota/nyc_manila_paris_bogota.csv

    Comment

    Working...
    X