Jiangtang's profile技止于此BlogListsNetwork Tools Help

Blog


    1/12/2008

    SAS Tips &Tricks:按组求累加值

    按组求累加值:原数据由下面给出:

    data a;
        input id sum;
    cards;
    1 4
    1 3
    2 5
    2 7
    2 9
    3 6
    3 6
    ;

    上面id分为1、2、3,要求按每组求累加值,即生成一个新变量cum,它看起来是这样的:

    id    sum    cum
    1     4       4
    1     3       7
    2     5       5
    2     7      12
    2     9      21
    3     6       6
    3     6      12

    方案一:

    proc sort data=a;
        by id;
    run;

    data b;
        set a;
        by id;

    retain cum;
    if first.id then cum=sum ;
            else cum=cum+sum;
    run;

    方案二(方案一的小改进):

    proc sort data=a;
        by id;
    run;

    data b;
        set a;
        by id;
        if first.id then cum=sum ;
            else cum+sum;
    run;


    Comments (2)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Nov. 9
    Nov. 3

    Trackbacks

    The trackback URL for this entry is:
    http://johnthu.spaces.live.com/blog/cns!2053CD511E6D5B1E!367.trak
    Weblogs that reference this entry
    • None