【问题标题】:New column in the start of a data table数据表开头的新列
【发布时间】:2018-02-24 14:12:13
【问题描述】:

我可以像这样向 data.table 添加一个新列:

DT = data.table(A=sample(3, 10, TRUE), 
         B=sample(letters[1:3], 10, TRUE), C=sample(10))

DT[, new:=1:10]

但是有没有一种巧妙的方法可以将其设置为 data.table 的开头? - 我知道我可以用 setcolorder 做到这一点,但我想避免这种情况。

setcolorder(DT, c("new", "A", "B", "C"))

【问题讨论】:

  • 如果您主要关心的是行,您可以将它们全部组合在一行中:setcolorder(DT[, new: = 1:10], c('new', 'A', 'B', 'C')),但您仍会使用setcolorder..

标签: r data.table add calculated-columns


【解决方案1】:

您可以尝试DT <- data.table(New = c(1:10), DT),它将新列放置在数据表的开头。

【讨论】:

    【解决方案2】:

    你可以使用cbind():

    DT = data.table(A=sample(3, 10, TRUE), 
                    B=sample(letters[1:3], 10, TRUE), C=sample(10))
    
    cbind(new=1:10, DT)
    #    new A B  C
    # 1:   1 2 b  8
    # 2:   2 3 b 10
    # 3:   3 1 b  1
    # 4:   4 1 a  5
    # 5:   5 2 a  6
    # 6:   6 3 c  2
    # 7:   7 3 a  3
    # 8:   8 1 a  4
    # 9:   9 1 a  7
    #10:  10 3 c  9
    

    【讨论】:

      猜你喜欢
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2021-11-24
      • 2022-10-20
      • 2014-11-02
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多