我有以下SAS数据集:
data mydata;
LENGTH id 4.0 num 4.0 A $ 4. B $ 8. C $ 20.;
input id num A $ B $ C $;
datalines;
1 1 x yy zzzzz
2 1 x yy zzzzz
3 2 xq yyqq zzzzzqqqqq
4 1 x yy zzzzz
5 3 xqw yyqqww zzzzzqqqqqwwwww
6 1 x yy zzzzz
7 4 xqwe yyqqwwee zzzzzqqqqqwwwwweeeee
;看起来就像
mydata
-------------------
id num A B C
1 1 x yy zzzzz
2 1 x yy zzzzz
3 2 xq yyqq zzzzzqqqqq
4 1 x yy zzzzz
5 3 xqw yyqqww zzzzzqqqqqwwwww
6 1 x yy zzzzz
7 4 xqwe yyqqwwee zzzzzqqqqqwwwwweeeee问题是,每个num >1的观测实际上包含了多个“观察”的数据,我想使用SAS中的一些逻辑将其分解。下面是我想要得到的一个例子:
mydatawanted
-------------------
id num A B C
1 1 x yy zzzzz
2 1 x yy zzzzz
3 1 x yy zzzzz
3 1 q qq qqqqq
4 1 x yy zzzzz
5 1 x yy zzzzz
5 1 q qq qqqqq
5 1 w ww wwwww
6 1 x yy zzzzz
7 1 x yy zzzzz
7 1 q qq qqqqq
7 1 w ww wwwww
7 1 e ee eeeee基本上,如果num > 1,我想根据每个变量的长度,为每个项接受每个变量的子字符串,然后以num =1作为新的观察输出这些变量。
data mydata2(drop=i _:);
set mydata; /*use the data from the original data set */
_temp_id = id; /*create temp variables from the currently read observation */
_temp_num = num;
_temp_A = A;
_temp_B = B;
_temp_C = C;
if (_temp_num > 1) THEN /* if num in current record > 1 then split them up */
do i = 1 to _temp_num;
id = _temp_id; /* keep id the same */
num = 1; /* set num to 1 for each new observation */
A = substr(_temp_A,i,i); /*split the string by 1s */
B = substr(_temp_B,1 + 2 * (i - 1),i * 2); /*split the string by 2s */
C = substr(_temp_C,1 + 5 * (i - 1),i * 5); /*split the string by 5s */
OUTPUT; /* output this new observation with the changes */
end;
else OUTPUT; /* if num == 1 then output without any changes */
run;然而,它并不像我所希望的那样起作用(我发表了一些评论,以显示我认为每一步都发生了什么)。它实际上产生了以下结果:
mydata2
-------------------
id num A B C
1 1 x yy zzzzz
2 1 x yy zzzzz
3 1 x yy zzzzz
3 1 q qq qqqqq
4 1 x yy zzzzz
5 1 x yy zzzzz
5 1 qw qqww qqqqqwwwww
5 1 w ww wwwww
6 1 x yy zzzzz
7 1 x yy zzzzz
7 1 qw qqww qqqqqwwwww
7 1 we wwee wwwwweeeee
7 1 e ee eeeee这个mydata2结果与mydatawanted不一样。num =1的行很好,但是当num >1时,输出记录与我想要的有很大不同。但是,记录的总数是正确的。我不太清楚发生了什么,因为这是我第一次尝试像这样复杂的SAS逻辑,但我希望在修复代码或使用任何替代方法完成我想做的事情方面提供任何帮助。谢谢!
编辑:,我修复了原来输入mydata数据语句的一个问题,并更新了这个问题。
发布于 2014-03-26 14:08:24
你的子子不对。Substr采用参数(original string, start, length),而不是(original string, start, ending position)。所以length应该是1,2,5而不是i,i*2,i*5。
A = substr(_temp_A,i,1); /*split the string by 1s */
B = substr(_temp_B,1 + 2 * (i - 1),2); /*split the string by 2s */
C = substr(_temp_C,1 + 5 * (i - 1),5); /*split the string by 5s */https://stackoverflow.com/questions/22662620
复制相似问题