如何删除SAS数据集Dairy1中变量名的前缀下划线?
Fixing Variable Rename in SAS for Leading Underscores
It looks like your original code had a couple of key issues that prevented it from working correctly. Let's break down the problems and fix them step by step.
Why Your Original Code Failed
- Incorrect Filtering: Your
WHEREclause'240' = scan(name, 2, '_')only targets the single variable_240, not all variables like_241,_242, etc. - Invalid Rename Syntax: Using
scan(name, 1, '_')on a variable name starting with_returns an empty string (since the first character is the delimiter), leading to broken rename statements like_240=. - Case Sensitivity: SAS stores dataset names in uppercase in the
dictionary.columnstable, somemname = 'Dairy1'won't match your dataset (it’s stored asDAIRY1).
Corrected Solution
First, generate a valid list of rename statements using PROC SQL, then apply the renames with either a data step or PROC DATASETS (more efficient for just renaming variables).
Step 1: Generate the Rename List
proc sql noprint; select cats(name, '=', substr(name, 2)) into :rename_list separated by ' ' from dictionary.columns where libname = 'WORK' /* Adjust if your dataset is in another library */ and memname = 'DAIRY1' /* Must be uppercase */ and name like '_%'; /* Select all variables starting with underscore */ quit; %put &rename_list.; /* Verify output (e.g., _240=240 _241=241) */
Step 2: Apply the Renames
Option 1: Rename variables in-place (no new dataset created):
proc datasets lib=WORK nolist; modify DAIRY1; rename &rename_list.; quit;
Option 2: Create a new dataset with renamed variables:
data want; set WORK.DAIRY1; rename &rename_list.; run;
Alternative: Rename Without Macro Variables
If you prefer avoiding macro variables, you can use PROC DATASETS with a direct RENAME statement, but the macro approach is more flexible for dynamic variable lists.
内容的提问来源于stack exchange,提问作者Juan Felipe M Rocha
相关产品推荐
相关产品推荐

