Announcement

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

  • Creation of New Variable from Long Variable

    Hello Everyone,

    I am currently working on a "long" variable of 9 digits and want to make a new variable consisting of first 4 digits of long variable. I used the following command where x is the long variable and y is new first four element variable:

    gen id=string(x)
    gen y=substr(id,1,4)

    However, i am getting decimals whereas the original long variable do not have decimals example:
    for x=110100101
    i am getting y = 1.10
    whereas it want is 1101

    Please Help. Thanks in advance.

    Regards






  • #2
    The function string() will use the default numerical formatting for a long number, which is scientific notation. To get around that, explicitly format the string conversion by using the optional second argument to the string() function.

    .ÿsetÿobsÿ1
    numberÿofÿobservationsÿ(_N)ÿwasÿ0,ÿnowÿ1

    .ÿgenerateÿlongÿxÿ=ÿ110100101

    .ÿgenerateÿstrÿidÿ=ÿstring(x,ÿ"%09.0f")

    .ÿgenerateÿstrÿyÿ=ÿsubstr(id,ÿ1,ÿ4)

    .ÿlist,ÿnoobs

    ÿÿ+------------------------------+
    ÿÿ|ÿÿÿÿÿÿÿÿÿxÿÿÿÿÿÿÿÿÿÿidÿÿÿÿÿÿyÿ|
    ÿÿ|------------------------------|
    ÿÿ|ÿ110100101ÿÿÿ110100101ÿÿÿ1101ÿ|
    ÿÿ+------------------------------+

    .


    See
    Code:
    help string()
    for details.

    Comment


    • #3
      Dear Joseph Coveney, thank you so much for the detailed explanation. It was really helpful, i learned a lot and the problem is resolved.

      Comment

      Working...
      X