Announcement

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

  • Reshape issues

    Dear all,
    maybe this question will make smile several of you, but now I am facing some difficulties to resolve it.
    I got a matrix with data (580+k) on three variables (2 string, 1 double) and I am trying to reshape it wide from long. Stata do not accept that the j(var) have names with spaces, but I am obliged to use that.
    As in the do file I have also a variable (str5 "Code") that would allow to resolve this problem because it is uniquely linked to one (origin) of the two string variables that I need to use to perform the reshape, I am trying to replicate the variable (str5) to the second string variable (destination), but I need to respect the unique linkage with the new variable.



    Click image for larger version

Name:	Immagine2.png
Views:	1
Size:	18.6 KB
ID:	1640108


    I am trying to perform a trivial foreach loop, but I cannot arrive to find the good sintax.

    Code:
    gen code_dest= Code
    
    foreach i in origin {
        replace code_dest=... if ...
    }
    Hope someone could help me to find a plausible solution to that. Thanks.



  • #2
    See the function -strtoname()-

    Code:
    help strtoname()

    ADDED IN EDIT: I may have misunderstood what you want. The above will allow you to transform destination to a name string that reshape can handle. If you mean that there is a 1:1 correspondence between code and origin, but you want to map code to destination, then

    Code:
    preserve
    keep code origin
    rename (code origin) (code2 destination)
    contract code2 destination
    tempfile code
    keep code2 destination
    save `code'
    restore
    merge m:1 destination using `code', nogen
    Last edited by Andrew Musau; 08 Dec 2021, 13:46.

    Comment


    • #3
      Another solution would be

      Code:
      gen code2 = code if origin == destination
      bys destination (code2): replace code2 = code2[_N]

      Comment


      • #4
        Thanks you all, I resolved that! Now I have my 764x764 matrix of distances and I can perform the simulation I have in mind! Thanks a lot!
        D.

        Comment

        Working...
        X