我正在嘗試編寫一個腳本來對數據表中存在的特定列求和。 讓我們稱它們為 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 << 獲取列名( string );這使得每個返回的列名都是一個字符串,這就是用戶定義列的列表。我一開始沒有抓住那個不好。
以下是您可以做什麼的幾個示例。 有更簡單(更容易理解)的方法來過濾找到的列,但是關聯數組適合這種類型的用例
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));
))
));
首先,我使用以下方法計算所需列表中數據表中存在哪些列關聯數組和相交. 然後有兩個選項,使用 << 設置每個值和數據表下標計算總和或構建公式表達式並使用那