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?