转置在SAS中保留id变量的多个值的所有组合

时间:2013-09-05 14:54:11

标签: sas transpose

我想将一个表从long转换为宽,但每个Key都有多个值。我希望转置表对于Id和Key的每个组合都有一行,所以对于这个示例项,我在转置后会有8行。 Id变量将被保留,每个不同的Key将是同一个键的不同值的所有组合。所以2 * 2 * 1 * 1 * 1 * 2 = 8行。

data grades;
input Id Key $ Value $;
cards;
219381 Category Something
219381 Category Another
219381 Color    White
219381 Color    Black
219381 Sport    Football
219381 Gender   Male
219381 Size     Big
219381 Quality  Good
219381 Quality  Bad
;
run;

这是我想在这种复杂的换位之后得出的结论:

Id      Category  Color Sport    Gender Size Quality
219381  Something White Football Male   Big  Good
219381  Something White Football Male   Big  Bad
219381  Something Black Football Male   Big  Good
219381  Something Black Football Male   Big  Bad
219381  Another   White Football Male   Big  Good
219381  Another   White Football Male   Big  Bad
219381  Another   Black Football Male   Big  Good
219381  Another   Black Football Male   Big  Bad

我是如何实现这一目标的? 我尝试过很多事情都没有成功。

2 个答案:

答案 0 :(得分:2)

对我来说,这看起来像是想要一个存储在一个表中的不同键的笛卡尔积。虽然不是非常类似于SAS,但是您可以通过在同一个表上使用PROC SQL连接来为这些不同的键类型模拟各个表,从而获得您正在寻找的结果。

PROC SQL;
    CREATE TABLE grades_combos AS
    SELECT DISTINCT 
        g.id, category.value as category, color.value as color, sport.value as sport,
        gender.value as gender, size.value as size, quality.value as quality
    FROM grades g
    INNER JOIN grades category ON category.id = g.id AND category.key = 'Category'
    INNER JOIN grades color ON color.id = g.id AND color.key = 'Color'
    INNER JOIN grades sport ON sport.id = g.id AND sport.key = 'Sport'
    INNER JOIN grades gender ON gender.id = g.id AND gender.key = 'Gender'
    INNER JOIN grades size ON size.id = g.id AND size.key = 'Size'
    INNER JOIN grades quality ON quality.id = g.id AND quality.key = 'Quality'

    ORDER BY id, category, color, sport, gender, size, quality
    ;
QUIT;

你可能会使这个更灵活和通用,也许将它包装在一个宏中,该宏根据一组任意键生成JOIN语句。

答案 1 :(得分:0)

从头脑中,我可以想到以下两种方法:

  1. 使用旁白声明? (需要排序数据)
  2. 创建第三个变量,它是另一个变量的串联 变量并使用那个。