-
Notifications
You must be signed in to change notification settings - Fork 29
/
varconvert.ado
77 lines (63 loc) · 1.75 KB
/
varconvert.ado
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// This function is very slow. Only use it when the size of the data is not big
// ============================================================================
program varconvert, rclass
// -------------------------------------------------------------------------
// Check the variable type
// =========================================================================
capture confirm variable `0'
if _rc != 0 {
display as err "variable `0' was not found"
error 198
}
capture confirm numeric variable `0'
if _rc == 0 {
local type numeric
}
else {
local type string
}
local data
local N = _N
// Converting numeric variable
// -------------------------------------------------------------------------
if "`type'" == "numeric" {
forval i = 1/`N' {
//avoid the first comma
if !missing("`data'") local data "`data',"
//turn missing to NA
if !missing(`0'[`i']) {
local data : display "`data'" `0'[`i']
}
else {
local data : display "`data'" "NA"
}
}
}
// Converting string variable
// -------------------------------------------------------------------------
else {
forval i = 1/`N' {
//avoid the first comma
if !missing(`"`macval(data)'"') local data "`data',"
//turn missing to NA
if !missing(`0'[`i']) {
local data : display `"`macval(data)'"' `"""' `0'[`i'] `"""'
}
else {
local data : display `"`macval(data)'"' "NA"
}
}
}
// Return R code to reconstruct the variable
// -------------------------------------------------------------------------
local code "c(`data')"
display as txt `"{p}`code'"'
if "`type'" == "numeric" {
return local `0' "`code'"
return local type "numeric"
}
else {
return local `0' `"`macval(code)'"'
return local type "string"
}
end