编写可能缺少列引用的公式的最佳方法我有一个脚本,它会根据对象的内容创建一个公式。在某些情况下,填充对象的条目会被忽略。例如,在这种情况下,`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() 函数,但这很可能会导致公式运行速度非常慢,我不建议这样做)。我提供了一些避免重复计算的选项。您也可以创建一个函数来创建列/添加公式。