Announcement

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

  • Extract digits from a number

    We have a variable total_response_time formatted in an hour_minute_second way. For example 12301 means 1hour 23 minutes and 01 second, 423 means 4 minutes and 3 seconds, 113456 means 11 hours and 34 minutes and 56 seconds. How can we convert them into seconds? For example 12301 = 1*3600+23*60+1. The tricky part is that some of them have 6 digits, some 5 digits... Therefore, the following codes don't work

    gen x = totalresponsetime
    tostring x, gen(str_x)
    gen xhour=substr(str_x, 1, 2) //pull out the hours(1 means start at the first character and 2 means pull out 4 characters)
    gen xminutes=substr(str_x, 3, 2) //pull out the minutes (5 means start at the fifth character and 2 means pull out 2 characters)
    gen xseconds = substr(str_x, 5, 2) //pull out the seconds (8 means start at the eight character and 2 means pull out 2 characters)

  • #2
    Some of your wording doesn't match your code, but as you realise counting from the start of the string will indeed be wrong if you have different lengths of string.

    Here are two ways to do it:

    Code:
    clear 
    
    input ntest
    6
    57
    423 
    1234 
    12301
    113456 
    end 
    
    gen hours   = floor(ntest/10000)
    gen minutes = floor(mod(ntest, 10000)/100) 
    gen seconds = mod(ntest, 100) 
    
    
    list, sep(0)  
    
         +------------------------------------+
         |  ntest   hours   minutes   seconds |
         |------------------------------------|
      1. |      6       0         0         6 |
      2. |     57       0         0        57 |
      3. |    423       0         4        23 |
      4. |   1234       0        12        34 |
      5. |  12301       1        23         1 |
      6. | 113456      11        34        56 |
         +------------------------------------+
    
    drop seconds minutes hours 
    
    gen stest = string(ntest, "%06.0f") 
    
    gen hours   = real(substr(stest, -6, 2))   
    
    gen minutes = real(substr(stest, -4, 2))  
    
    gen seconds = real(substr(stest, -2, 2)) 
     
    list , sep(0) 
    
         +---------------------------------------------+
         |  ntest    stest   hours   minutes   seconds |
         |---------------------------------------------|
      1. |      6   000006       0         0         6 |
      2. |     57   000057       0         0        57 |
      3. |    423   000423       0         4        23 |
      4. |   1234   001234       0        12        34 |
      5. |  12301   012301       1        23         1 |
      6. | 113456   113456      11        34        56 |
         +---------------------------------------------+

    Comment

    Working...
    X