1

I have a data table with 3 columns.

> library(data.table)
> library(magrittr)
>
> myDT <- data.table(L = c(1.1,2.2), M = c(3.3, 4.4), R = c(5.5,6.6))
> myDT
     L   M   R
1: 1.1 3.3 5.5
2: 2.2 4.4 6.6

I want to round() 2 of the columns. It seems like the simplest approach would be to use the magrittr compound-assign operator, %<>%.

> myDT[, c('M', 'R')] %<>% round
> myDT
     L M R
1: 1.1 3 6
2: 2.2 4 7

This works fine, but if I try to use a vector of column names, it does not work.

> toRound <- c('M', 'R')
> myDT[, toRound] %<>% round
Error in `[.data.table`(myDT, , toRound) : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'toRound' is not found. Perhaps you intended DT[, ..toRound]....

Including with = FALSE also gives an error, even though removing %<>% round from the line gives the same subset of the data table in both cases.

> myDT[, c('M', 'R')]
     M   R
1: 3.3 5.5
2: 4.4 6.6
> myDT[, toRound, with = FALSE]
     M   R
1: 3.3 5.5
2: 4.4 6.6

Is it possible to use the compound-assign operator in a data table when using a vector of column names?

markus
  • 25,843
  • 5
  • 39
  • 58
sam
  • 501
  • 1
  • 4
  • 11
  • 4
    There is a feature request https://github.com/Rdatatable/data.table/issues/1208 Current standard way https://stackoverflow.com/questions/16846380/how-to-apply-same-function-to-every-specified-column-in-a-data-table – Frank 2 Dec 05 '19 at 00:24
  • 1
    Thanks @Frank2, that answers my question. Your answer to the question you linked provided a good explanation +1 – sam Dec 05 '19 at 17:54

0 Answers0