Announcement

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

  • Replacing Values for Multiple Variables at One Time

    I am trying to recode a set of 16 items from a survey, all of which use the same 4-point scale. Is there a way I can do this in one code instead of repeating the commands multiple times? Thanks!

  • #2
    Yes.

    If you are going to be using the -recode- command for this, -recode- accepts a whole list of variables, so just list them all and it will be done in one line.

    If you are using some other commands for this, then you can wrap them in a loop. Read -help foreach-, particularly -foreach … of varlist …-.

    If you need more specific advice, please show example data when posting back and also explain (or, better still, show the code for) the actual transformation you are appying to the variables. If you are running version 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Comment


    • #3
      [crossed in the ether with Clyde's response --- perhaps my stuff is useful anyway]
      The syntax diagram shown in -help recode- starts with -recode varlist ...-, meaning that you can recode a whole list of variables with a common coding rule. A trip through the PDF documentation from -help recode- is worth it, given that the first-line help doesn't detail all the possibilities of this command. (I learned some new stuff on this reading myself!) Note that use of the pre() option give to new names to you recoded variables and avoids overwriting your old variables. I also like the option to specify new label information on the fly.

      Code:
      recode YourVarlist (old stuff = new stuff "new label string") (   .....)   ..... , pre(New) label(YourNewValueLabelName)

      Comment


      • #4
        Clyde Schechter Thank you for your response. I am using the replace command because all of my data were imported as text. Here is an example of what I normally would do:
        replace q8_7="1" if q8_7=="Not Confident"
        replace q8_7="2" if q8_7=="Slightly Confident"
        replace q8_7="3" if q8_7=="Moderately Confident"
        replace q8_7="4" if q8_7=="Completely Confident"
        destring q8_7, replace force

        However, questions q8_1-q8_16 have the same exact values and will need the same transformation.

        Comment


        • #5
          You could use a foreach loop. Here's the basic idea:


          Code:
          foreach var of varlist [yourvar1 yourvar2 etc] {
          replace `var'="1" if `var'=="Not Confident"
          replace `var'="2" if `var'=="Slightly Confident"
          replace `var'="3" if `var'=="Moderately Confident"
          replace `var'="4" if `var'=="Completely Confident"
          destring `var' replace force
          }

          Comment


          • #6
            I would approach this differently. The code in #5 and your own code in #4 take you from an awkward string variable you can't compute with to a numeric variable where you will have to somehow remember what the different value 1, 2, 3, and 4 actually stood for originally when you come back and look at this a year from now. Also all your results tables will say 1, 2, 3, and 4, which means you'll need footnotes explaining them. Waste of time and ink (pixels). I would change these to value-labeled numeric variables. That's the best of both worlds: the underlying variables will be numeric, supporting calculations, but what you see in output displays will look like the original string variable.

            Code:
            label define confidence 1   "Not Confident" ///
                                    2   "Slightly Confident"    ///
                                    3   "Moderately Confident"  ///
                                    4   "Completely Confident"
            foreach v of varlist q8_1-q8_16 {
                encode `v', gen(_`v')
                order _`v', before(`v')
                drop `v'
                rename _`v', `v'
            }
            Note: the use of the variable list q8_1-q8_16 is only correct if these 16 variables are located consecutively in your data set. If other variables are interspersed among them, then you cannot use that shorthand and you will have to enumerate the 16 variables in the -foreach v of varlist…- command (or find a different shortcut that correctly identifies these and only these variables.)

            Comment


            • #7
              Thanks, Clyde Schechter. I already had a label defined for this and would've applied it once the variable was transformed. But I like your approach. Thanks for your help!
              Last edited by Tiara Rosemond; 23 Oct 2019, 14:55.

              Comment


              • #8
                I'd think that the not-so-well documented -label- option of -encode- would be relevant here so as to enforce the chosen coding.

                Comment


                • #9
                  Mike is absolutely right. I meant to include -label(confidence)- in the -encode- command in #6. My error, and my apologies.

                  Comment


                  • #10
                    Hi all,

                    I am quite new to stata! Great to find STATALIST. I am trying to label all my (string) variables that are coded as Yes/No with 0=no, 1=yes. I tried to do this with the code mentioned above (see adjusted version below). After this code I get the following error: factor-variable and time-series operators not allowed
                    r(101);

                    label define yesno 0 "no" ///
                    1 "yes" , replace
                    foreach v of varlist literacy literacycheck firsthusband bankaccount backaccother childmortality planmorechildren foodsecurity1 foodsecurity2 foodsecurity3 foodsecurity4 foodsecurity5 foodsecurity6 foodsecurity7 foodsecurity8 foodsecurity9 Nutrition_1 Nutrition_2 Nutrition_5 Nutrition_6 Nutrition_7 Nutrition_8 Nutrition_9 Nutrition_10 Toiletshare vegetablegarden assetsmatrix1_1 assetsmatrix1_2 assetsmatrix1_3 assetsmatrix1_4 assetsmatrix1_5 assetsmatrix1_6 assetsmatrix2_10 assetsmatrix2_11 assetsmatrix2_12 assetsmatrix2_13 assetsmatrix2_7 assetsmatrix2_9 assetsmatrix2_8 assetsmatrix3_14 assetsmatrix3_15 assetsmatrix3_16 assetsmatrix3_17 assetsmatrix3_18 assetsmatrix3_19 assetsmatrix3_20 assetsmatrix3_21 mosquitonets socialsupport_1 socialsupport_2 socialsupport_3 socialsupport_4 stereotypes_1 stereotypes_2 stereotypes_3 stereotypes_4 debt {
                    encode label(yesno) `v', gen(_`v')
                    order _`v', before(`v')
                    drop `v'
                    rename _`v', `v'
                    }

                    Would be great if someone would know how to deal with this!

                    Thank you in advance,

                    Linda

                    Comment


                    • #11
                      as per the help file, label() is an option and thus goes after the comma not where you put it; see
                      Code:
                      help encode

                      Comment


                      • #12
                        #10 was cross-posted at https://www.statalist.org/forums/for...me-via-foreach

                        Comment


                        • #13
                          Hi Rich, thank you for your response! The code worked, really happy thanks.

                          @Nick thank you for your response as well. I assume cross-posting is not preferred? Is it preferred to open a new question or respond under an existing one?

                          Have a great day,

                          Linda

                          Comment


                          • #14
                            You can post in an existing thread if your topic matches the thread title. Alternatively, you can start a new thread.

                            What isn't an especially good idea is to post essentially the same question more than once in different threads. Here, and often, it has led to repeated replies and some small waste of effort.

                            A small deal in the big scheme of things but just practical sense!

                            Comment


                            • #15
                              This threat has been very helpful, but I'm getting stuck on the code. Here is what I have:
                              label define confidence 1 "Strongly disagree" ///
                              2 "Somewhat disagree" ///
                              3 "Neither agree nor disagree" ///
                              4 "Somewhat agree" ///
                              5 "Strongly Agree"

                              foreach v of varlist q10_1 q10_2 q10_3 {
                              encode `v', gen(_`v') label(confidence)
                              order _`v', before(`v')
                              drop `v'
                              rename _`v', `v'
                              }

                              But unfortunately, I get this:
                              syntax error
                              Syntax is
                              rename oldname newname [, renumber[(#)] addnumber[(#)] sort ...]
                              rename (oldnames) (newnames) [, renumber[(#)] addnumber[(#)] sort ...]
                              rename oldnames , {upper|lower|proper}
                              r(198);


                              Any suggestions about how to fix the syntax?

                              Thank you,
                              Gene

                              Comment

                              Working...
                              X