hannes101 hannes101 - 3 months ago 7
R Question

set() in data.table - matching on names instead of column number

Using set() for efficiency to update values insided of a data.table I ran into problems, when the order of the columns changed. So to prevent that I used a workaround to match the column name instead of the column postion.
I would like to know if there's a better way of addressing the column in the j part of the set query.

DT <- as.data.table(cbind( Period = 1:10,
Col.Name=NA))

set(DT, i = 1L , j = as.integer(match("Col.Name",names(DT))), value = 0)
set(DT, i = 3L , j = 2L, value = 0)


So I would like to ask if there's a data.table workaround for this, perhaps a fast matching on the colnames already available.

Answer

We can use column name directly in 'j'

set(DT, i = 1L , j = "Col.Name", value = 0)
DT
#    Period Col.Name
# 1:      1        0
# 2:      2       NA
# 3:      3       NA
# 4:      4       NA
# 5:      5       NA
# 6:      6       NA
# 7:      7       NA
# 8:      8       NA
# 9:      9       NA
#10:     10       NA
Comments