我正在尝试编写一个脚本来对数据表中存在的特定列求和。 让我们称它们为 Col A、Col B、Col C、Col D。 问题是数据表并不总是包含导致错误的所有四列。 我想编写一个脚本,可以添加数据表中存在的 Col A、Col B、Col C 和 Col D。 显然我可以只更新每次出现的代码,但我正在尝试找到一种可以处理各种数据表而不会出错的自动化方法。
谢谢!
你好@DegreesOfGen19 ,
这与您正在寻找的相似吗?
Names default to here(1);
dt = current data table();
// your columns of interest
col_list = { "Col A", "Col B", "Col C", "Col D" };
// creates list of column names from the target data table
dt_col_list = dt << Get column names( string );
for( i = 1, i <= N Items( col_list ), i++,
if( contains( dt_col_list, col_list[i] ),
mysum = colsum( column( col_list[i] ) );
show( mysum )
)
);
编辑:更改 dt << 获取列名; to dt << 获取列名(字符串);这使得每个返回的列名都是一个字符串,这就是用户定义列的列表。我一开始没有抓住那个不好。
以下是您可以做什么的几个示例。 有更简单(更容易理解)的方法来过滤找到的列,但是关联数组适合这种类型的用例
Names Default To Here(1);
dt = New Table("Untitled 3",
Add Rows(1),
Compress File When Saved(1),
New Column("Column 1", Numeric, "Continuous", Set Values([1,2,3,.])),
New Column("Column 2", Numeric, "Continuous", Set Values([2,3,4,5])),
New Column("Column 3", Numeric, "Continuous", Set Values([3,4,5,.]))
);
col_list = {"Column 1", "Column 2", "Column 3", "Column 4"};
table_col_list = dt << Get Column Names("String");
// keep only columns which are found from data table
cols_to_keep = Associative Array(col_list);
cols_to_keep << Intersect(Associative Array(table_col_list));
cols_to_keep = cols_to_keep << get keys;
// if you don't need a formula, data table subscripting is quite easy solution
dt << New Column("SumForCols", Numeric, Continuous, << Set Each Value(
Sum(dt[Row(), cols_to_keep]);
));
// if you do need a formula, you can build one with expressions (requires JMP16+ due to For Each usage)
// https://community.jmp.com/t5/JSL-Cookbook/Insert-one-expression-into-another-using-Eval-Insert-Eval-Expr/ta-p/48998
f_expr = Expr(Sum());
For Each({col_name}, cols_to_keep,
Insert Into(f_expr, Name Expr(AsColumn(col_name)));
);
show(name expr(f_expr));
Eval(EvalExpr(
dt << New Column("SumForColsFormula", Numeric, Continuous, Formula(
Expr(name expr(f_expr));
))
));
首先,我使用以下方法计算所需列表中数据表中存在的列关联数组和相交. 然后有两个选项,使用 << 设置每个值和数据表下标计算总和或构建公式表达式并使用那