Data Table - Select Value of Column by Name From Another Column

前端 未结 3 1451
后悔当初
后悔当初 2020-12-04 02:31

I have a data table with a number of columns containing values. I have another column which defines which one of those columns whose value I need to select. I am having tr

相关标签:
3条回答
  • 2020-12-04 02:40

    You can use matrix indexing to pull values from the first and second columns:

    mx.idx <- d[, cbind(1:nrow(d), match(name.of.col, names(d)))]
    d[, 
      value.of.col:=
        as.matrix(d[, 1:2])[mx.idx]
     ]
    d
    #    value.1 value.2 name.of.col value.of.col
    # 1:     one     two     value.1          one
    # 2:     uno     dos     value.2          dos
    # 3:       1       2     value.1            1
    
    0 讨论(0)
  • 2020-12-04 02:43

    The following should be memory efficient and a little easier to read/follow.

    for (i in unique(d[["name.of.col"]]))
        d[ name.of.col==i, value.of.col:=get(i) ]
    
    d
       value.1 value.2 name.of.col value.of.col
    1:     one     two     value.1          one
    2:     uno     dos     value.2          dos
    3:       1       2     value.1            1
    
    0 讨论(0)
  • 2020-12-04 03:03

    Another option:

    d[ , value.of.col := diag(as.matrix(.SD)), .SDcols = d[ , name.of.col]]
    > d
       value.1 value.2 name.of.col value.of.col
    1:     one     two     value.1          one
    2:     uno     dos     value.2          dos
    3:       1       2     value.1            1
    

    EDIT add a faster solution:

    d[ , value.of.col :=
          melt(d,id.vars='name.of.col')[name.of.col==variable, value]]
    
    0 讨论(0)
提交回复
热议问题