Replace a Letter to 9999 and Convert to Number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | * (Q) My string variable contains a letter. I need to replace the letter by 9999 then convert the resulting variable to a number. * (A) Posted by Raynald Levesque in Dec 2002. DATA LIST LIST /rec(F3) var1(A8). * Use "," instead of "." in case your system settings use comma as a decimal separator. BEGIN DATA 1 546.23 2 25.2 3 31.28 4 V28.00 5 2B42. 6 20Z 7 29.C29 8 12345 END DATA. LIST. STRING var2(A13). * Use INDEX instead of CHAR.INDEX function at older SPSS versions. DO IF CHAR.INDEX(var1,".")=0. * Use "," instead of "." in case your system settings use comma as a decimal separator. - COMPUTE var2=CONCAT(RTRIM(var1),"."). ELSE. - COMPUTE var2=var1. END IF. EXECUTE. COMPUTE len2=LEN(RTRIM(var2)). LOOP cnt=1 TO len2. * Check actual letter ranges of your national alphabet. - DO IF RANGE(SUBSTR(var2,cnt,1),"a","Z"). - COMPUTE idx=cnt. - BREAK. - END IF. END LOOP. DO IF idx=1. COMPUTE var2=CONCAT("9999",SUBSTR(var2,2)). ELSE IF idx < len2. COMPUTE var2=CONCAT(SUBSTR(var2,1,idx-1),"9999",SUBSTR(var2,idx+1)). ELSE. COMPUTE var2=CONCAT(SUBSTR(var2,1,idx-1),"9999"). END IF. COMPUTE nb=NUMBER(var2,F10.2). FORMATS nb(F16.6). LIST var1 var2 nb. |
Related pages
...