Announcement

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

  • Reshape one to many of a string variable - error: ", not allowed"

    I am trying to reshape one string variable into many. I am getting an error that says ", not allowed"

    the variable I want to reshape, var1, is coded like this
    ID var1
    1 a, 2b, c
    2 1a, b
    3 3a,
    4 2a, 2b, 3b
    but when I try the code:
    gen byte var1_long_ = 1
    reshape wide var1_long_, i(ID) j(var1) string


    I get an error ", not allowed"

    How can I code so that the commas are not used in the new variable names, just the numbers and letters ?

  • #2
    What you are trying to do is not reshaping the dataset. To split your var1 into multiple variables based on comma you can use:
    split var1, parse(",")

    Comment


    • #3
      What I want is to create new variables for each unique observation (i.e var1_a, var1_2b, etc.) and give a value of 1 / 0 for each ID if the observation is present.
      I don't think split does that

      Comment


      • #4
        The split is the first step, then you can use reshape twice on the variables created by split. Something like the following.
        Code:
        * Example generated by -dataex-. To install: ssc install dataex
        clear
        input byte d str10 var1
        1 "a, 2b, c"  
        2 "1a, b"     
        3 "3a,"       
        4 "2a, 2b, 3b"
        end
        split var1, parse(",") generate(v)
        list, clean
        drop var1
        reshape long v, i(d) j(seq)
        replace v = trim(v)
        list, clean
        drop seq
        drop if missing(v)
        generate v_ = 1
        reshape wide v_, i(d) j(v) string
        list, clean
        for which the end result is
        Code:
        . list, clean
        
               d   v_1a   v_2a   v_2b   v_3a   v_3b   v_a   v_b   v_c  
          1.   1      .      .      1      .      .     1     .     1  
          2.   2      1      .      .      .      .     .     1     .  
          3.   3      .      .      .      1      .     .     .     .  
          4.   4      .      1      1      .      1     .     .     .

        Comment


        • #5
          I just wish to remark the recommendation to use name plus family name, as explained in the FAQ.

          In case of registering without full name, the recommended step is to click on the 'contact us' button and inform the correct name. Thanks.
          Best regards,

          Marcos

          Comment


          • #6
            Thanks William,
            I think this will give me what I need, much appreciated.

            Comment

            Working...
            X