【发布时间】:2018-02-13 09:27:30
【问题描述】:
我有一个包含 4 年数据(2014-2017)的数据集。 我想给每个观察结果一个包含来自 if 标准的 E、E/F 或 F 的周期变量。
我通过在数据步骤中每年重复我的代码来让它工作:
新数据; 旧的;
format period $10.;
if year=2014 then do;
if start<'01feb2014'd and end<='01mar2014'd then period='E';
else if start<'01feb2014'd and end>'01mar2014'd then period='E/F';
else if start>='01feb2014'd then period='F';
end;
if year=2015 then do;
if start<'01feb2015'd and end<='01mar2015'd then period='E';
else if start<'01feb2015'd and end>'01mar2015'd then period='E/F';
else if start>='01feb2015'd then period='F';
end;
if year=2016 then do;
if start<'01feb2016'd and end<='01mar2016'd then period='E';
else if start<'01feb2016'd and end>'01mar2016'd then period='E/F';
else if start>='01feb2016'd then period='F';
end;
if year=2017 then do;
if start<'01feb2017'd and end<='01mar2017'd then period='E';
else if start<'01feb2017'd and end>'01mar2017'd then period='E/F';
else if start>='01feb2017'd then period='F';
end;
运行;
但我想通过使用 af do 循环来更智能地编写代码。 我试过这个:
新数据; 旧的;
format period $10.;
do i=0 to 3;
if year=(2014+i) then do;
if start<'01feb(2014+i)'d and end<='01mar(2014+i)'d then period='E';
else if start<'01feb(2014+i)'d and end>'01mar(2014+i)'d then period='E/F';
else if start>='01feb(2014+i)'d then period='F';
end;
end;
运行;
但这并不能给出 2015-2017 年的正确结果。
我也试过这个:
新数据; 旧的;
format period $10.;
do i=2014 to 2017;
if year=(i) then do;
if start<'01feb(i)'d and end<='01mar(i)'d then period='E';
else if start<'01feb(i)'d and end>'01mar(i)'d then period='E/F';
else if start>='01feb(i)'d then period='F';
end;
end;
运行;
但是代码连运行都跑不了?
我错过了什么??
亲切的问候。
【问题讨论】:
标签: loops date if-statement sas