編寫可能缺少列引用的公式的最佳方法我有一個腳本,它會根據物件的內容創建一個公式。在某些情況下,填充物件的條目會被忽略。例如,在這種情況下,`N Items(yVars) == 0`。如何才能讓公式在列為空時忽略列引用進行計算?
下面的範例過於複雜,我檢查是否存在某個條目,並使用 If() 語句來建立替代操作。
If( N Items( yVars ) == 0,
Data Table( "HIRP" ) << New Column( "Average PTC",
Numeric,
"Continuous",
Format( "Best", 12 ),
Formula(
Col Mean(
Col Maximum( :Power, :Heater, :HD_NUM ),
:Heater,
:WAFER_SUBSTRATE_LOT_ID_IDX
)
)
),
Eval(
Eval Expr(
Data Table( "HIRP" ) << New Column( "Average PTC",
Numeric,
"Continuous",
Format( "Best", 12 ),
Formula(
Col Mean(
Col Maximum( :Power, :Heater, :HD_NUM ),
:Heater,
Expr(
Name Expr( As Column( Divider ) )
)
)
)
)
)
)
);
自動化和腳本編寫回覆:寫出可能缺少列引用的公式的最佳方法以下是一種方法:
//first a table to add columns to
Names default to here(1);
dt = New Table( "Test Table",
Add Rows( 2 ),
New Column( "a", Numeric, "Continuous", Format( "Best", 12 ), Set Values( [1, 2] ) )
);
//this one does create a column
if(!Contains(dt << get column names("string"), "b"),
dt << New Column( "b", Numeric, "Continuous", Format( "Best", 12 ), Set Values( [3, 4] ) )
);
//this does not since b already exists
if(!Contains(dt << get column names("string"), "b"),
dt << New Column( "b", Numeric, "Continuous", Format( "Best", 12 ), Set Values( [5, 6] ) )
);
回覆:寫出可能缺少列引用的公式的最佳方法您目前這樣做有什麼特殊原因嗎?如果列引用為空,請不要將其新增至公式。
你的方法其實並不複雜,而且易於閱讀和理解。你可以使用 if 語句來設定公式,這樣可以稍微減少重複程式碼。我會選擇這兩種方法,或是你現在的方法(如果我理解你的問題沒錯的話)。
Names Default To Here(1);
// myvar = 1;
dt = Open("$SAMPLE_DATA/Big Class.jmp");
newcol = dt << New Column("Test", Numeric, Continuous);
If(Is Missing(myvar),
newcol << Set Formula(
:height/:weight
);
,
newcol << Set Formula(
:weight/:height
)
);
一些更難閱讀、理解和調試的選項:
您可以在 IF 語句中建立公式表達式,然後設定公式
Names Default To Here(1);
myvar = 1;
dt = Open("$SAMPLE_DATA/Big Class.jmp");
fexpr = If(Is Missing(myvar), Name Expr(:height/:weight), Name Expr(:weight/:height));
Eval(EvalExpr(
newcol = dt << New Column("Test", Numeric, Continuous, Formula(
Expr(NameExpr(fexpr))
))
));
或者你可以在公式求值中使用 if 語句(在我看來,這樣做沒必要這麼複雜)。
Names Default To Here(1);
dt = Open("$SAMPLE_DATA/Big Class.jmp");
newcol = dt << New Column("Test", Numeric, Continuous);
Eval(Substitute(
Expr(newcol << Set Formula(
_fexpr_
)),
Expr(_fexpr_), If(Is Missing(myvar), Name Expr(:height/:weight), Name Expr(:weight/:height))
));
回覆:寫出可能缺少列引用的公式的最佳方法我對目前方法的主要不滿在於它看起來過於臃腫。同一段程式碼有兩個版本,一個包含中間列,一個不包含。我以為會有一個類似 Try() 語句的東西來處理這種不一致性。類似的方法也能讓編輯過程更方便。
回覆:寫出可能缺少列引用的公式的最佳方法公式中缺少列引用的情況無法直接處理(雖然可以使用 Try() 函數,但這很可能會導致公式運行速度非常慢,我不建議這樣做)。我提供了一些避免重複計算的方案。您也可以建立一個函數來建立列/新增公式。