Reference a column by a variable

吃可爱长大的小学妹 提交于 2021-01-27 18:31:10

问题


I want to reference a table column by a variable while creating another column but I can't get the syntax:

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

I get the error the record's field 'c0' was not found. It is understanding c0 as a literal but I want the text value contained in c0. How to do it?

Edit

I used this inspired by the accepted answer:

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

回答1:


Another way:

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



回答2:


try using an index as below

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



回答3:


Expression.Evaluate is another possibility:

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

Please refer to this article to understand the [_=_] context argument:

Expression.Evaluate() In Power Query/M

This article explains that argument specifically:

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.



来源:https://stackoverflow.com/questions/61825560/reference-a-column-by-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!