Announcement

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

  • Using Stata in a jupyter notebook: how do you use inline python variables in the command string passed to "stata.run".

    Thank you for reading.

    First, I apologise if my question doesn't meet the exact requirements of the forum

    I have a simply question regarding the integration of Stata in a jupyter notebook.

    I want to run the following python code


    Code:
    for user in users:
        stata.run("stcox observer_uip_pioped if user_id==user")

    I simply want to know how you can embed python variables into the string that is passed to

    Code:
    stata.run
    Thanks

  • #2
    Simon Walsh,

    In your case, it looks like each element in the Iterable users is an integer. If yes, you can run

    Code:
    for user in users:
        stata.run("stcox observer_uip_pioped if user_id==" + str(user))
    You need to convert the integer user to a string using the str() method before concatenating it to another string. Take the following as an example:

    Code:
    >>> stata.run('sysuse auto, clear')
    (1978 automobile data)
    >>> for i in [0,1]:
    ...     stata.run('summ price if foreign==' + str(i))
    ...
    
        Variable |        Obs        Mean    Std. dev.       Min        Max
    -------------+---------------------------------------------------------
           price |         52    6072.423    3097.104       3291      15906
    
        Variable |        Obs        Mean    Std. dev.       Min        Max
    -------------+---------------------------------------------------------
           price |         22    6384.682    2621.915       3748      12990
    Similarly, if you want to pass a string Iterator, you can do the following:

    Code:
    >>> maker = ['AMC Concord', 'AMC Pacer']
    >>> for m in maker:
    ...     stata.run('list price mpg if make=="' + m + '"')
    ...
    
         +-------------+
         | price   mpg |
         |-------------|
      1. | 4,099    22 |
         +-------------+
    
         +-------------+
         | price   mpg |
         |-------------|
      2. | 4,749    17 |
         +-------------+

    Comment

    Working...
    X