我有一个数字变量(例如,圆柱体),我想将其覆盖为字符(并使其在表中的顺序保持一致)。
我想一步来做。有什么聪明的方法吗?
data cars; set sashelp.cars;
if cylinders >= 6 then cylinders = 'Big';
if cylinders < 6 then cylinders 'Ecocar';
run;
我只是试图避免创建新的字符变量,然后不得不将该新的字符变量重新定位到表中圆柱体位置的繁琐步骤。
尝试使用Proc格式
Proc format;
Value CylSize
0 - 6 = ‘Ecocar’
7 - high = ‘Big’;
Run;
Data cars;
Set sashelp.cars;
Format Cylinders CylSize.;
Run;
一旦定义了变量,就不能在不创建新变量的情况下将其从一种类型更改为另一种类型。在制作之前,您需要定义它在表中的位置。快速的方法是在retain
语句之前使用set
语句来定义预先存在的变量的顺序,而不必担心它们的类型。
data cars;
retain make model type origin drivetrain _cylinders;
length cylinders $15.;
set sashelp.cars(rename=(cylinders = _cylinders));
if _cylinders >= 6 then cylinders = 'Big';
if _cylinders < 6 then cylinders = 'Ecocar';
drop _cylinders;
run;
另一种方法是,首先创建一个虚拟表,该虚拟表看起来完全符合您的期望,并具有所需的所有变量属性。只用一个空行填充它,以便以后重新排列很容易。我们称它为cars_attribs
。例如:
Type C C C C C C N N N ...
Column make model type origin drivetrain cylinders msrp invoice enginesize ...
Row . . . ...
在带有set
的obs=0
语句中使用此表以始终保留您喜欢的变量位置。
data cars;
set cars_attribs(obs=0)
sashelp.cars(rename=(cylinders = _cylinders));
;
if _cylinders >= 6 then cylinders = 'Big';
if _cylinders < 6 then cylinders = 'Ecocar';
drop _cylinders;
run;
如果您要更改可变位置,只需通过拖动列来重新排列《企业指南》中的cars_attribs
。
您可以查询元数据以找到变量的顺序,并使用该顺序在正确的位置定义新变量。
但是让我们假设,如果变量的顺序对您如此重要,那么您已经知道第一个变量的名称是什么。
通过使用基于位置的变量列表,仅包括CYLINDERS之前的变量。然后定义您的新变量。然后再次使用所有变量重新读取观察值,以使CYLINDERS之后的变量出现在新变量之后。
现在添加代码以填充新变量。放下旧的。并将新名称重命名为旧名称。
因此,如果第一个变量名为MAKE,则您的代码如下所示:
data want ;
set sashelp.cars(keep=MAKE -- CYLINDERS);
length new_var $10 ;
set sashelp.cars;
if cylinders >= 6 then new_var = 'Big';
else if not missing(cylinders) then new_var = 'Ecocar';
drop CYLINDERS;
rename new_var=CYLINDERS;
run;
您可以使用重命名并保留:
data cars(drop=temp);
retain Make Model Type Origin DriveTrain MSRP Invoice EngineSize cylinders Horsepower
MPG_City MPG_Highway Weight Wheelbase Length;
set sashelp.cars(rename=(cylinders=temp));
if temp >= 6 then cylinders = 'Big';
if temp < 6 then cylinders = 'Ecocar';
run;
您也可以使用proc sql:
proc sql;
create table cars as
select Make, Model, Type, Origin, DriveTrain, MSRP, Invoice, EngineSize,
case when cylinders >= 6 then 'Big'
when cylinders < 6 then 'Ecocar' end as cylinders,
Horsepower, MPG_City, MPG_Highway, Weight, Wheelbase, Length
from sashelp.cars
;
quit;