我有一個垂直數據集,每個案例的年數數據(例如體重)不均勻。 有些有 1、2、3、4、6 年,有些有 3、4、5 年。 我希望每個案例都有 6 行,其中年份列包含 1、2、3、4、5、6,即使其中一些年份沒有體重。 如何為每個案例分配 6 行以識別適當的缺失年份?
假設您有大量數據,可以使用一個簡單的腳本來添加缺失的年份。下面是一個示例,它創建了一個缺少一些年份的原始表,然後從這一點開始執行幾個步驟,最終將缺少的年份添加到
names default to here(1);
dt = New Table( "Base",
Add Rows( 10 ),
New Column( "Case",
Numeric,
"Continuous",
Format( "Best", 12 ),
Set Values( [1, 1, 1, 1, 1, 2, 2, 2, 2, 2] ),
Set Display Width( 43 )
),
New Column( "Year",
Numeric,
"Continuous",
Format( "Best", 12 ),
Set Values( [1, 2, 3, 5, 6, 1, 2, 4, 5, 6] )
),
New Column( "OtherStuff", formula(randomuniform()))
);
// Summarize original data table to get a data table of the cases
dtCase = dt << Summary(
Group( :Case ),
Freq( "None" ),
Weight( "None" ),
output table name( "Cases" )
);
dtCase << delete columns(:N Rows);
// Create a new table with just the years
dtYears = new table("years", new column("Year", values([1,2,3,4,5,6])));
// Perform a cartesian join to create a table with all combinations of cases and years
dtCY = Data Table( "Cases" ) << Join(
With( Data Table( "years" ) ),
Cartesian Join,
Output Table( "Case and Years" )
);
// Use a join on the original table to add in the misssing years
dt << Join(
With( dtCY ),
Merge Same Name Columns,
Match Flag( 0 ),
By Matching Columns( :Case = :Case, :Year = :Year ),
Drop multiples( 0, 0 ),
Include Nonmatches( 0, 1 ),
Preserve main table order( 1 ),
Output Table( "Final" )
);
這行得通! 我不得不分配到我的原始表來獲取案例,但整體方法工作正常。 非常感謝!