通过变量引用列

Reference a column by a variable

我想在创建另一列时通过变量引用 table 列,但我无法获得语法:

    t0 = Table.FromRecords({[a = 1, b = 2]}),
    c0 = "a", c1 = "b",
    t1 = Table.AddColumn(t0, "c", each([c0] + [c1]))

我收到错误消息未找到记录的字段'c0'。它将 c0 理解为文字,但我想要 c0 中包含的文本值。怎么做?

编辑

我使用这个灵感来自于公认的答案:

    t0 = Table.FromRecords({[a = 1, b = 2]}),
    c0 = "a", c1 = "b",
    t1 = Table.AddColumn(t0, "c", each(Record.Field(_, c0) + Record.Field(_, c1)))

尝试使用如下索引

let t0 = Table.FromRecords({[a = 1, b = 2]}),
#"Added Index" = Table.AddIndexColumn(t0, "Index", 0, 1),
c0 = "a",
c1 = "b",
t1 = Table.AddColumn(#"Added Index", "c", each Table.Column(#"Added Index",c0){[Index]} + Table.Column(#"Added Index",c1){[Index]} )
in t1

另一种方式:

let
    t0 = Table.FromRecords({[a = 1, b = 2]}),
    f = {"a","b"},
    t1 = Table.AddColumn(t0, "sum", each List.Sum(Record.ToList(Record.SelectFields(_, f))))
in
    t1

Expression.Evaluate是另一种可能:

= Table.AddColumn(t0, "c", each Expression.Evaluate("["&c0&"] + ["&c1&"]", [_=_]) )

请参阅本文以了解 [_=_] 上下文参数:

Expression.Evaluate() In Power Query/M

This article 具体解释了该论点:

Inside a table, the underscore _ represents the current row, when working with line-by-line operations. The error can be fixed, by adding [_=_] to the environment of the Expression.Evaluate() function. This adds the current row of the table, in which this formula is evaluated, to the environment of the statement, which is evaluated inside the Expression.Evaluate() function.