Hi JSL programmers,
I had a little problem as part of a larger application and thought I'd share it with you, and see if there's a way to do it better/slicker.
Basically I have a vector of 1s and 0s (i.e. [1, 1, 0, 0, 1]) that I need to convert to a string of Ys and Ns (i.e. "YYNNY"). Then I need to do the reverse, that is convert a string of Ys and Ns back to a vector of 1s and 0s.
Here are my quick and dirty functions - let's see if you can come up with something beyond my feeble brainpower!
// Convert a vector of 1s and 0s to a string with no separators
matrix_10_to_yn = function({matrix_10}, {default local},
yn_txt = "";
if (nrows(matrix_10) > 0,
// Strip out square brackets and commas
yn_txt = substitute(char(matrix_10), "[", "", "]", "", ", ", "");
// Now convert 1s to Y and 0s to N
yn_txt = substitute(yn_txt, "1", "Y", "0", "N");
);
yn_txt;
);
// Convert a YN string with no separators to a vector of 1s and 0s
yn_to_matrix_10 = function({yn_txt}, {default local},
n = length(yn_txt);
matrix_10 = j(n, 1, 0);
for (i = 1, i <= n, i++,
if (substr(yn_txt, i, 1) == "Y",
matrix_10[i] = 1;
);
);
matrix_10;
);
// Test thing out
a = yn_to_matrix_10("YYYNNNN"); show(a);
b = matrix_10_to_yn(a); show(b);
c = yn_to_matrix_10(""); show(c);
d = matrix_10_to_yn(c); show(d);