【问题标题】:Filtering Columns by name in SASFiltering Columns by name in SAS
【发布时间】:2022-12-27 12:08:45
【问题描述】:

I have a data set that contains year month in column names and I need get the data from column that contains the last date:

data have;
input sdo_202211 sdo_202210 sdo_202209;
datalines;
30 20 10
50 20 30
;
run;

Shape of result:

sdo_202211
30
50

【问题讨论】:

  • What is the shape of your desired result?
  • What are you going to do with a dataset that just has the one variable separated from all of the other variables? Doesn't it lose most of its meaning if you do that?

标签: loops sas filtering calculated-columns sas-macro


【解决方案1】:

Since your data always follows the format sdo_yyyymm, we can pull the yyyymm part, convert it to a SAS date, and find the maximum date. We'll use dictionary.columns to read all of the column names from the dataset.

proc sql;
    select name
    into :max_date
    from dictionary.columns
    where libname = 'WORK' AND memname = 'HAVE'
    having input(scan(name, -1, '_'), yymmn6.) = max(input(scan(name, -1, '_'), yymmn6.) )
    ;
quit;

input(scan(name, -1, '_'), yymmn6.) pulls the yyyymm part from the column name, then converts it into a SAS date.

This code saves the variable name into a macro variable called max_date. Now we can grab only the column with the max date, even if the variables are ever shuffled out-of-order:

data want;
    set have(keep=&max_date);
run;

Output:

sdo_202211
30
50

【讨论】:

    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 2022-12-26
    相关资源
    最近更新 更多