Dear statalisters,
Have you noticed this behavior of levelsof: the number of elements in the macro it creates and in r(levels) is one more than it should be. This can create errors and undesirable consequences when looping over all elements of that macro. Or if one wants to assign the contents of that macro to be rownames or colnames of a matrix, one gets conformability error.
Is this intended? If yes, how can one drop the last blank element?
Have you noticed this behavior of levelsof: the number of elements in the macro it creates and in r(levels) is one more than it should be. This can create errors and undesirable consequences when looping over all elements of that macro. Or if one wants to assign the contents of that macro to be rownames or colnames of a matrix, one gets conformability error.
Is this intended? If yes, how can one drop the last blank element?
Code:
* gen 4 obs capture set obs 4 gen var_num = _n * see how levelsof processes these 4 obs levelsof var_num, l(values_num) * count number of elements in the local created by levelsof local count_values_num: word count of `values_num' di "Number of numeric values: `count_values_num'" * display each element in turn forvalues i = 1/`count_values_num' { local l: word `i' of `values_num' di "Word `i' of values_num: `l'" } * * what happens when the variable is type string * label the numeric variable and then decode it label define var_num_label 1 "A X" 2 "B Y" 3 "C Z" 4 "D W" label values var_num var_num_label decode var_num, g(var_str) * levelsof with default compound quotes levelsof var_str, l(values_str) local count_values_str: word count of `values_str' di "Number of string values: `count_values_str'" * display each element in turn forvalues i = 1/`count_values_str' { local l: word `i' of `values_str' di "Word `i' of values_str: `l'" } * * beware of option clean when spaces in strings * levelsof, clean, i.e. no compound quotes levelsof var_str, l(values_str_cl) clean local count_values_str_cl: word count of `values_str_cl' di "Number of string values: `count_values_str_cl'" * display each element in turn forvalues i = 1/`count_values_str_cl' { local l: word `i' of `values_str_cl' di "Word `i' of values_str_cl: `l'" } * * last, try to use the contents of levelsof to assign names of the rows or columns of a matrix mat C = (1,2,3,4\5,6,7,8\9,11,22,33\44,55,66,77) mat colnames C = "(1)" "(2)" "(3)" "(4)" mat rownames C = "row 1" "row 2" "row 3" "row 4" matlist C mat rownames C = "`values_str'"
Comment