如何在 SAS 中创建数据透视表? [英] How can I create pivot table in SAS?

查看:146
本文介绍了如何在 SAS 中创建数据透视表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据集中有三列:spendage_bucketmultiplier.数据看起来像......

I have three columns in a dataset: spend, age_bucket, and multiplier. The data looks something like...

spend   age_bucket  multiplier
10      18-24        2x
120     18-24        2x
1       35-54        3x

我想要一个数据集,其中列作为年龄桶,行作为乘数,条目作为支出列的总和(或其他聚合函数).是否有 proc 来执行此操作?我可以使用 proc SQL 轻松完成它吗?

I'd like a dataset with the columns as the age buckets, the rows as the multipliers, and the entries as the sum (or other aggregate function) of the spend column. Is there a proc to do this? Can I accomplish it easily using proc SQL?

推荐答案

有几种方法可以做到这一点.

There are a few ways to do this.

data have;
input spend   age_bucket $ multiplier $;
datalines;

10      18-24        2x
120     18-24        2x
1       35-54        3x
10      35-54        2x
;

proc summary data=have;
var spend;
class age_bucket multiplier;
output out=temp sum=;
run;

首先,您可以使用 PROC Summary 计算相关变量的聚合,在本例中为 sum.CLASS 语句为您提供了总和.这将计算 N-Way 和,输出数据集将包含它们.运行代码并查看数据集 temp.

First you can use PROC SUMMARY to calculate the aggregation, sum in this case, for the variable in question. The CLASS statement gives you things to sum by. This will calculate the N-Way sums and the output data set will contain them all. Run the code and look at data set temp.

接下来您可以使用 PROC TRANSPOSE 来旋转表格.我们需要使用 BY 语句,因此需要 PROC SORT.我还会过滤到您关心的聚合.

Next you can use PROC TRANSPOSE to pivot the table. We need to use a BY statement so a PROC SORT is necessary. I also filter to the aggregations you care about.

proc sort data=temp(where=(_type_=3));
by multiplier;
run;

proc transpose data=temp out=want(drop=_name_);
by multiplier;
var spend;
id age_bucket;
idlabel age_bucket;
run;

在传统模式下,35-54 不是有效的 SAS 变量名.SAS 会将您的列转换为专有名称.变量上的标签将保留原始值.请注意,如果您以后需要引用该变量,名称已更改为有效.

In traditional mode 35-54 is not a valid SAS variable name. SAS will convert your columns to proper names. The label on the variable will retain the original value. Just be aware if you need to reference the variable later, the name has changed to be valid.

这篇关于如何在 SAS 中创建数据透视表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆