You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SAS技术咨询:如何将指定两列拆分为目标四列

SAS Data Reshaping: Split Columns by Type Value

Got it, let's tackle this SAS data reshaping problem. You need to pivot your dataset so that the type values become suffixes for your Group1 and Group2 columns, matching the rows between the value and percent groups. Here are two straightforward approaches:

Approach 1: Using PROC TRANSPOSE (Clean & Scalable)

This method is great if you might add more group columns later, since it's easy to extend.

First, let's create your test dataset to work with:

/* Create the input dataset */
data have;
    input Group1 Group2 type $;
    datalines;
1.1 1.4 value
0.5 0.4 value
5 6 percent
4 10 percent
;
run;

Next, add a row ID to each observation within its type group—this ensures we match the correct rows between value and percent:

/* Add row identifier for matching rows across types */
data have_with_id;
    set have;
    by type;
    if first.type then rowid = 1;
    else rowid + 1;
run;

Now transpose Group1 and Group2 separately, then merge the results:

/* Transpose Group1 to get Group1_value and Group1_percent */
proc transpose data=have_with_id out=group1_trans prefix=Group1_;
    by rowid;
    id type;
    var Group1;
run;

/* Transpose Group2 to get Group2_value and Group2_percent */
proc transpose data=have_with_id out=group2_trans prefix=Group2_;
    by rowid;
    id type;
    var Group2;
run;

/* Merge the two transposed datasets and clean up */
data want;
    merge group1_trans group2_trans;
    by rowid;
    drop rowid _name_;
run;

Approach 2: Using DATA Step (Flexible for Custom Logic)

If you prefer more control over the row matching process, this DATA step method works well:

data want;
    /* First, read all "value" observations and initialize the target columns */
    do until(last.value);
        set have(where=(type='value'));
        Group1_value = Group1;
        Group2_value = Group2;
        output;
    end;
    rewind; /* Reset the input pointer to the start of the dataset */

    /* Now read "percent" observations and map them to the existing rows */
    do i = 1 to nobs;
        set have(where=(type='percent')) nobs=nobs point=i;
        set want point=i;
        Group1_percent = Group1;
        Group2_percent = Group2;
        output;
    end;
    stop; /* Prevent infinite loop */

    /* Drop unused variables */
    drop Group1 Group2 type i;
run;

Both methods will produce your desired output:

Group1_value Group1_percent Group2_value Group2_percent
1.1 5 1.4 6
0.5 4 0.4 10

内容的提问来源于stack exchange,提问作者Pari T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:32:50