Announcement

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

  • Create a calculated variable for each variable with same prefix

    Hi,

    I have a dataset that looks like the below (except there are like 15 n_* variables).
    state n_women n_men n_dogs
    TX 20 25 40
    VA 30 10 10
    NY 20 15 25
    CA 10 5 15
    I want to loop through all the variables beginning with n_ and create a new variable for each with the suffix "_average" that is divided by 5 (so looking like this):
    state n_women n_men n_dogs n_women_average n_men_average n_dogs_average
    TX 20 25 40 4 5 8
    VA 30 10 10 6 2 2
    NY 20 15 25 4 3 5
    CA 10 5 15 2 1 3
    How do I get to this? Right now I am trying this:

    local a = r(varlist)
    local b state
    local c: list a-b

    foreach x in local c {
    gen `x'_average=`x'/5
    }

    I get the error that " is not a valid command name". I've tried a bunch of different ways, and am just not coming up with an answer, I know there are a bunch of different ways to do it, but I just need one to work, haha.

    Thank you in advance!!



  • #2
    Code:
    foreach var of varlist n_*{
        gen `var'_average= `var'/5
    }

    Comment


    • #3
      Wow that was quick! I think that works, now some of the variable names are just too long. I think it will work but I'll just need to rename some of the wordier ones. thanks

      Comment


      • #4
        You can do something like

        Code:
        rename n_*_average *_avg

        Comment

        Working...
        X