【问题标题】:Assign column names to a data.table whose name is selected from another data.table将列名分配给名称选自另一个 data.table 的 data.table
【发布时间】:2018-01-15 10:39:44
【问题描述】:

我必须将列名分配给一系列数据表,这些数据表的名称存储在另一个 data.table 中(将其解释为配置表)。例如,在下面的示例中,我想将DT1 的 2 列命名为“id”和“name”。我知道我必须这样命名DT1 的列,因为DT1DT2 中:

col1 = 1:5
col2 = LETTERS[1:5]
DT1 = data.table(col1, col2)

id = 1
name = "DT1"
DT2 = data.table(id, name)

columnNames = c('ID', 'Letter')

我可以这样做

DT3 = eval(as.name(DT2[1, name]))
colnames(DT3) = columnNames 

x = DT2[1, name]

assign(x, DT3)

但是,我不喜欢这样,因为我将 DT1 复制到 DT3,这会减慢我的程序。

显然,这不起作用:

colnames(eval(as.name(DT2[1, name]))) = columnNames
colnames(get(DT2[1, name])) = columnNames 

有没有办法在不复制 data.table 的情况下为 data.table 分配列名(当 data.table 的名称只能从另一个 data.table 中选择时)?

【问题讨论】:

    标签: r dataframe data.table


    【解决方案1】:

    你可以使用data.table::setnames:

    setnames(get(DT2[1, name]), columnNames)
    DT1
    #   id Letter
    #1:  1      A
    #2:  2      B
    #3:  3      C
    #4:  4      D
    #5:  5      E
    

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2016-02-02
      • 1970-01-01
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      • 1970-01-01
      • 2017-06-13
      相关资源
      最近更新 更多