身份证号码6回报'体重不足'什么时候应该回归'超重' 有问题的代码行,第30-53行,包含嵌套的if语句,并产生一个不良结果。这些方法的目的是将样本分为权重类别:体重不足,平均或超重。
TITLE 'A SHORT SAS PROGRAM';
OPTIONS LS=72;
* Create data file with height and weight data;
DATA HTWT;
INPUT ID GENDER $ HEIGHT WEIGHT;
DATALINES;
1 M 68.5 155.0
2 F 61.2 99.00
3 F 63.0 115.0
4 M 70.0 205.0
5 M 68.6 170.0
6 F 65.1 125.0
7 M 72.4 220.0
;
* Create a new categorical variable for height;
DATA HTWT;
SET work.HTWT;
IF HEIGHT < 68 THEN
STATURE='Short';
IF HEIGHT >=68 THEN
STATURE='Tall';
RUN;
* Create a new categorical variable for weight;
DATA HTWT;
SET work.HTWT;
IF GENDER='M' THEN
IF WEIGHT > 170 THEN
WEIGHT_CLASS='Overweight';
IF 170 >=WEIGHT >=150 THEN
WEIGHT_CLASS='Average';
IF WEIGHT < 140 THEN
WEIGHT_CLASS='Underweight';
ELSE IF GENDER='F' THEN
IF WEIGHT > 120 THEN
WEIGHT_CLASS='Overweight';
IF 120 >=WEIGHT >=100 THEN
WEIGHT_CLASS='Average';
IF WEIGHT < 100 THEN
WEIGHT_CLASS='Underweight';
RUN;
* Changing units of height from inches to centimeters;
DATA HTWT;
SET work.HTWT;
HEIGHT=2.54 * HEIGHT;
RUN;
* Creates HEALTH_INDEX;
DATA HTWT;
SET work.HTWT;
HEALTH_INDEX=WEIGHT/HEIGHT;
RUN;
* Print the data file HTWT;
PROC PRINT DATA=HTWT;
TITLE 'HEIGHT AND WEIGHT DATA';
RUN;
* Sorts the data by gender. Some procedures require sorted data;
PROC SORT DATA=HTWT OUT=sorted;
BY GENDER;
RUN;
* Print the sorted data file;
PROC PRINT DATA=sorted;
TITLE 'GENDER SORTED HTWT DATA';
RUN;
答案 0 :(得分:1)
将嵌套的if语句修改为:
IF GENDER='M' THEN do;
IF WEIGHT > 170 THEN
WEIGHT_CLASS='Overweight';
else if 150 <= Weight <= 170 THEN
WEIGHT_CLASS='Average';
else
WEIGHT_CLASS='Underweight';
end;
else do;
IF WEIGHT > 120 THEN
WEIGHT_CLASS='Overweight';
else iF 100 <= Weight =< 120 THEN
WEIGHT_CLASS='Average';
else
WEIGHT_CLASS='Underweight';
end;
看看它是否有效?
答案 1 :(得分:1)
请不要接受我的答案作为正确答案,因为我迟到了,而且普遍的答案是明确和有用的。 但是我在这里给你一个简单的建议,当你必须连接很多嵌套的if语句时,请使用select when语句(来自sql语言)为所有可能变量的值提供一个层。
data want;
set have;
if gender='M' then do;
select (weight);
when (>x) weight_class='';
when (<y) weight_class='';
otherwise weight_class=''
end;
end;
else if gender='F' then do;
select (weight);
when (>x) weight_class='';
when (<y) weight_class='';
otherwise weight_class=''
end;
end;
run;
答案 2 :(得分:0)
按顺序处理连续的IF语句。因此,最后一个是测试WEIGHT是否&lt;当然,第6号当然是6号被列为体重不足。 如果要控制执行顺序,请添加一些ELSE和/或DO / END块。你的基本结构可能应该是这样的。
if A then do;
if B then xxx ;
else if C then xxx ;
else if D then xxxx ;
end;
答案 3 :(得分:0)
如果语句有用,但有时创建格式并使用put语句来执行分配更安全。如果你不得不做很多IF,尤其如此,至少在我的情况下,我做的打字越多,我搞砸的机会就越大。
使用put语句的代码更容易检查和维护。