1

我想将表格从长转换为宽,但每个键都有多个值。我希望转置表对于 Id 和 Key 的每个组合都有一行,因此对于此示例项目,我在转置后将有 8 行。将保留 Id 变量,每个不同的键将是同一键的不同值的所有组合。所以 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

有什么想法可以实现这一目标吗?我尝试了很多事情都没有成功。

4

2 回答 2

2

对我来说,这看起来像是您想要一个用于存储在一个表中的不同键的笛卡尔积。虽然不太像 SAS,但获得所需结果的一种方法是PROC SQL在同一个表上使用 with 连接,模拟这些不同键类型的各个表。

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于任意一组键生成语句。

于 2013-09-05T19:03:36.833 回答
0

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

  1. 使用副词?(需要排序数据)
  2. 创建第三个变量,它是其他 2 个变量的串联并使用该变量。
于 2013-09-05T15:46:43.780 回答