【问题标题】:Converting Rows containing Years into Columns将包含年份的行转换为列
【发布时间】:2010-11-18 19:29:53
【问题描述】:

为了将数据输入 SAS,需要采用以下格式:

Country Year Indicator_1
Belgium 1900 x1
Belgium 1901 x2
...
Belarus 1901 x1

但是,我的大部分数据都采用以下格式:

Country 1900 1901 1902 ... etc
Belgium x1____x2___x3  ...etc
Belarus x1____x2___x3  ...etc

是否有简单的宏或 VBA 脚本可以提供帮助?

【问题讨论】:

  • 你可以使用 awk 或类似的东西吗?这样更容易!

标签: excel ms-access sas


【解决方案1】:

将指标字符串解析为年份变量

假设有超过 3 年的数据,您需要调整引用 Y1900-Y1902 的格式和数组。

data original;
    infile datalines;
    format Country $20. YearIndicator $50.;
    input Country YearIndicator;

    format Y1900-Y1902 $4.;
    array y(*) y1900-y1902;
    do i = 1 to dim(y);
        y[i] = scan(YearIndicator,i,'_');
    end;
    drop i;
datalines;
Belgium x1____x2___x3
Belarus x1____x2___x3
run;

让宽桌子变高

proc transpose data=original out=talldata(rename=(_NAME_=CYear COL1=Indicator));
    by country notsorted;
    var y1900-y1902;
run;

将年份变量设为数字,而不是字符

data talldata;
    format Country $20. Year 4. Indicator $4.;
    set talldata;
    year=input(compress(cyear,,'kd'),4.);
    drop cyear;
run;

查看结果

proc print data=talldata; run;

输出

Obs    Country                 Year    Indicator

 1     Belgium                 1900      x1
 2     Belgium                 1901      x2
 3     Belgium                 1902      x3
 4     Belarus                 1900      x1
 5     Belarus                 1901      x2
 6     Belarus                 1902      x3

【讨论】:

  • 只是好奇:compres() 中的“kd”是做什么的?
  • compress 函数中,kd 作为第三个参数告诉 sas 到 k(eep) d(igits)。
【解决方案2】:

您可以使用联合查询:

SELECT Country, 1900 As SYear, [1900] As Indicator FROM Table
UNION ALL
SELECT Country, 1901 As SYear, [1901] As Indicator FROM Table

<..>

UNION ALL
SELECT Country, 2010 As SYear, [2010] As Indicator FROM Table

如果无法导出查询,您可以使用它来创建表。

【讨论】:

    【解决方案3】:

    如果输入的原始数据足够规则,则可以通过如下简单的数据步骤轻松完成。

       data one;
         infile cards dlm=" _" missover;
         input country :$20. @;
         do year = 1900 to 1902;
           input indicator $ @;
           output;
         end;
       cards;
       Belgium x1____x2___x3
       Belarus x4____x5___x6
       ;
       run;
    
       /* check */
       proc print data=one;
       run;
       /* on lst
       Obs    country    year    indicator
        1     Belgium    1900       x1
        2     Belgium    1901       x2
        3     Belgium    1902       x3
        4     Belarus    1900       x4
        5     Belarus    1901       x5
        6     Belarus    1902       x6
       */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-18
      • 2021-10-16
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 2011-01-02
      相关资源
      最近更新 更多