全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 SAS专版
1322 5
2013-10-08
悬赏 100 个论坛币 已解决
有如下数据集:

data a;
if _n_<8 then g=1;else g=2;
input x $ @@;
y=dif(x);
cards;
07 12 13 14 15 19 22 23 24 29 30 31 32 36
;run;

想得到如下效果:g=1 result='07,12-15,19,22' ; g=2 result='23-24,29-32,36'
意思就是按照g来分组,将x进行汇总,得到的字符串如有连号,用‘-’连接。

问题貌似不难,但是想了一个晚上,很受打击。。。

貌似按照y=dif(x)可以算,但是感觉写出来会很啰嗦,不知有没有更简洁的办法,我记得前段时间貌似坛子里看到过。。

One way as follow:

data b;set a;
retain z 0;
if y^=1 then z+1;
run;


..... Still have a loooooong way to go .....

最佳答案

pobel 查看完整内容

data a; if _n_1 or last.g); set a; by g x; if first.g then result=x; if y=1 then do;flag=1; tmp=x;end; end; if flag=1 then do; result=catx("-",result,tmp); if not last.g or y>1 then result=catx(", ",result,x); end; else result=catx(", ",result,x); if last.g then output; keep g result; run;
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2013-10-8 23:58:40
data a;
if _n_<11 then g=1;else g=2;
input x $ @@;
y=dif(x);
cards;
07 08 09 12 13 14 15 19 21 22 23 24 29 30 31 32 36
;run;

data c;
   length result $100;
   retain result;
   flag=0;
   do until(y>1 or last.g);
      set a;
          by g x;
          if first.g then result=x;
          if y=1 then do;flag=1; tmp=x;end;
   end;
   if flag=1 then do;
        result=catx("-",result,tmp);
        if not last.g or y>1 then result=catx(", ",result,x);
          end;
   else result=catx(", ",result,x);

   if last.g then output;
   keep g result;
run;
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2013-10-9 08:16:19
比较常规的方法:
data a;
if _n_<8 then g=1;else g=2;
input x $ @@;
y=dif(x);
cards;
07 12 13 14 15 19 22 23 24 29 30 31 32 36
;run;

data b;
   set a;
   by g;
   length result $100 tmp $8;
   retain flag 0 tmp result;
   if first.g then do; result=x; flag=0; tmp=" "; end;
   else do;
       if y ne 1 then do;
               if flag=0 then result=catx(", ",result,x);
                           else if flag=1 then result=catx(", ",catx("-",result,tmp),x);
                           flag=0;
                        end;
       else if y=1 then do;
               flag=1;
               tmp=x;
                           if last.g then result=catx("-",result,tmp);
            end;
   end;
   if last.g;
   keep g result;
run;

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2013-10-9 08:25:52
pobel 发表于 2013-10-9 08:16
比较常规的方法:
data a;
if _n_
谢谢pobel,需要很强的逻辑。
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2013-10-9 11:38:37
pobel 发表于 2013-10-8 23:58
data a;
if _n_1 or last.g);
      set a;
有个问题有点疑惑,可能还是涉及到PDV的问题,

在第一个loop里面,set a在do until里面和在do until之外有什么区别呢?

能不能麻烦讲讲其中的逻辑呢?

是不是第一个do loop就是把flag的值按照y的值全部赋值好以后,然后再进行下面的if else的语句呢

其实,在看你的那个常规方法的时候,那种疑惑更大,
尤其是在那个else do的循环里面,能不能麻烦仔细讲讲那个循环里面的逻辑呢
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2013-10-9 11:52:15
复制代码
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群