Dear Statalisters,
I am trying to change the names to all variables in my dataset to their variable labels but also adding a prefix of s if the variable string and n if the variable is numeric.
Please let me know what is wrong with the following code? It is giving an error related to brackets among others.
The problem is the variables start with a number, but the label is informative. I would like the variable to become the label but with a prefix depending on its format.
Thank you for your help,
May
* Step 1: Store variable labels in local macros
foreach var of varlist _all {
local label`var' : variable label `var'
}
* Step 2: Clean and rename variables using their labels and add appropriate prefix
foreach var of varlist _all {
local newname = `"`label`var''"'
* Clean the new name: replace spaces with underscores, remove special characters, and shorten if necessary
local newname = subinstr(`"`newname'"', " ", "_", .) // Replace spaces with underscores
local newname = subinstr(`"`newname'"', ".", "", .) // Remove periods
local newname = subinstr(`"`newname'"', ",", "", .) // Remove commas
local newname = substr("`newname'", 1, 32 - 2) // Truncate to fit with prefix (2 characters for prefix)
* Determine the prefix based on variable type
local prefix
if strpos("`: type `var''", "str") {
local prefix "s_"
} else {
local prefix "n_"
}
* Add prefix
local newname = "`prefix'`newname'"
if "`newname'" != "" {
rename `var' `newname'
}
}
I am trying to change the names to all variables in my dataset to their variable labels but also adding a prefix of s if the variable string and n if the variable is numeric.
Please let me know what is wrong with the following code? It is giving an error related to brackets among others.
The problem is the variables start with a number, but the label is informative. I would like the variable to become the label but with a prefix depending on its format.
Thank you for your help,
May
* Step 1: Store variable labels in local macros
foreach var of varlist _all {
local label`var' : variable label `var'
}
* Step 2: Clean and rename variables using their labels and add appropriate prefix
foreach var of varlist _all {
local newname = `"`label`var''"'
* Clean the new name: replace spaces with underscores, remove special characters, and shorten if necessary
local newname = subinstr(`"`newname'"', " ", "_", .) // Replace spaces with underscores
local newname = subinstr(`"`newname'"', ".", "", .) // Remove periods
local newname = subinstr(`"`newname'"', ",", "", .) // Remove commas
local newname = substr("`newname'", 1, 32 - 2) // Truncate to fit with prefix (2 characters for prefix)
* Determine the prefix based on variable type
local prefix
if strpos("`: type `var''", "str") {
local prefix "s_"
} else {
local prefix "n_"
}
* Add prefix
local newname = "`prefix'`newname'"
if "`newname'" != "" {
rename `var' `newname'
}
}
Comment