1

我有一个表,其列是动态的,除了一列:A。该表中还有一些空值 (0n)。如何添加另一列显示每行的总数,或者忽略该特定行中具有“0n”的列,或者在其位置取 0。这是我的代码,它在总和上失败,也不会忽略空值。

addTotalCol:{[]
    table:flip`A`B`C`D!4 4#til 9;
    colsToSum: string (cols table) except `A;   / don't sum A
    table: update Total: sum (colsToSum) from table;  / type error here. Also check for nulls
    :table;
   } 
4

2 回答 2

3

I think it is better to use functional update in your case:

addTotalCol:{[]
    table:flip`A`B`C`D!4 4#til 9;
    colsToSum:cols[table] except `A;   / don't sum A
    table:![table;();0b;enlist[`Total]!enlist(sum;enlist,colsToSum)];
    :table;
   }

Reason why it is not working is because your fourth line is parsed as:

table: update Total: sum (enlist"B";enlist"C";enlist"D") from table;

Since sum only works with numbers, it returns 'type error since your inputs are string.

Another solution to use colsToSum as string input:

addTotalCol:{[]
    table:flip`A`B`C`D!4 4#til 9;
    colsToSum:string cols[table] except `A;   / don't sum A
    table:get"update Total:sum(",sv[";";colsToSum],") from table"
    :table;
   }

Basically this will build the query in string before it is executed in q.

Still, functional update is preferred though.

EDIT: Full answer to sum 0n:

addTotalCol:{[]
    table:flip`A`B`C`D!4 4#0n,til 9;
    colsToSum:cols[table] except `A;   / don't sum A
    table:![table;();0b;enlist[`Total]!enlist(sum;(^;0;enlist,colsToSum))];
    :table;
   }
于 2014-03-25T14:57:45.310 回答
2

我认为这里有一个更简洁的版本,没有功能形式。

q)//let us build a table where our first col is symbols and the rest are numerics,
  /// we will exclude first from row sums
q)t:flip `c0`c1`c2`c3!(`a`b`c`d;1 2 3 0N;0n 4 5 6f;1 2 3 0Nh)
q)//columns for sum
q)sc:cols[t] except `c0
q)///now let us make sure we fill in each column with zero,
  /// add across rows and append as a new column
q)show t1:t,'flip enlist[`sumRows]!enlist sum each flip  0^t sc
c0 c1 c2 c3 sumRows
-------------------
a  1     1  2
b  2  4  2  8
c  3  5  3  11
d     6     6
q)meta t1
c      | t f a
-------| -----
c0     | s
c1     | i
c2     | f
c3     | h
sumRows| f
于 2014-03-26T13:47:32.560 回答