Announcement

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

  • create local with substring of varnames

    Hi everyone!
    Is there a way of creating a local with substrings of some variables' name in the dataset?
    I’ll give an example to make clear the point.

    Example:
    I have a dataset with two groups of variables (group “hello”, group “goodbye”).
    All the variables have a prefix A(“N”), with N that in principle can take any integer, but here say N ranges from 1 to 5.

    The variables names are:
    A1_hello A2_hello A3_hello A4_hello A5_hello; A3_goodbye A4_goodbye A5_goodbye.
    I would like to create a new variable that is the result of the multiplication between the variables goodbye and hello but only when they have the same prefix A(“N”) (i.e. A3_hello x A3_goodbye3; A4_hello x A4_goodbye; A5_hello x A5_goodbye).

    To do so, I thought it may be convenient to define a local that contains the digits before the underscore in the variables name belonging to the “goodbye” group (that is the least numerous group) and create a loop over these elements.

    local prefix ???
    local prefix should capture the prefixes A3 A4 A5


    foreach p in local prefix {
    gen `p'_hello_goodbye = `p'_hello * `p'_goodbye
    }

    This is a toy example to make clear what I need to do. If my explanation wasn’t clear enough do not hesitate to ask me more details, I’ll answer asap!
    Thanks for your attention!
    Last edited by Federico Stronati; 18 Jul 2023, 10:52. Reason: local substring

  • #2
    Code:
    g A1_junk = 1
    g A2_junk = 2
    g A3_junk = 3
    foreach p of varlist A* {
        summ `p'
    }

    Comment

    Working...
    X