我有一个数据集,其中有几个变量,后缀与给定日期相对应。我想用日期替换后缀,以使我的输出表更加用户友好。
以下是我的代码示例
我的sales
数据集中的字段是
product
number_of_sales_1
number_of_sales_2
number_of_sales_3
revenue_1
revenue_2
revenue_3
tax_1
tax_2
tax_3
后缀1,2,3对应于第二个数据集中保存的日期,格式如下
dates
id
date
1
01Apr
2
01May
3
01Jun
我想用日期批量替换后缀,以便sales
中的字段变为
product
number_of_sales_01Apr
number_of_sales_01May
number_of_sales_01Jun
revenue_01Apr
revenue_01May
revenue_01Jun
tax_01Apr
tax_01May
{{ 1}}
tax_01Jun
中的日期数量和指标数量都是动态的,因此我无法在代码中进行硬编码。
答案 0 :(得分:3)
我假设您的数据集如下所示:
data sales;
product="abc";number_of_sales_1=1;number_of_sales_2=2;number_of_sales_3=3;
revenue_1=1000;revenue_2=2000;revenue_3=3000;tax_1=100;tax_2=200;tax_3=300;
run;
data dates;
id=1;date="01Apr";output;id=2;date="01May";output;id=3;date="01Jun";output;
run;
proc contents data=sales out=sales_temp(keep=name) noprint; run;
data sales_temp1;
length check_date_vars $1. id 8.;
set sales_temp;
check_date_vars=compress(substr(name,length(name)));
temp=notdigit(check_date_vars);
if temp=0 then id=check_date_vars;
run;
proc sort data=sales_temp1; by id; run;
proc sort data=dates; by id; run;
data sales_temp_date;
merge sales_temp1(in=a) dates(in=b);
by id;
if a and b;
new_name=substr(name,1,length(name)-1)||date;
run;
proc sql noprint;
select count(*) into :num_vars separated by " " from sales_temp_date;
quit;
proc sql noprint;
select name into:old_name1 - :old_name&num_vars. from sales_temp_date;
select new_name into:new_name1 - :new_name&num_vars. from sales_temp_date;
quit;
%macro rename();
proc datasets library=work nolist;
modify sales;
rename
%do i=1 %to &num_vars.;
&&old_name&i.= &&new_name&i.
%end;
;
run;
%mend;
%rename;