You can create and assign objects in j , just use { curly brackets } .
You can then pass these objects (or functions and object calculations) from j and assign them as columns of a data table. To assign columns more than once at a time, simply:
- wrap
LHS in c(.) make sure the column names are strings and - the last line
j (ie the value of "return") should be a list.
dat[ , c("NewIncomeComlumn", "AnotherNewColumn") := { RelativeIncome <- Income/.SD[Nation == "A", Income]; RelativeIncomeLog2 <- log2(RelativeIncome);
You can think of j as a function in the dat environment
You can also get much more complicated and complex if required. You can also include by arguments using by=list(<someName>=col)
In fact, like functions, just creating an object in j and assigning a value to it does not mean that it will be accessible outside j . For it to be assigned to your data table., You must return it. j automatically returns the last line; if this last row is a list, each list item will be treated as a column. If you assign by reference (i.e. Using := ), you will achieve the expected results.
In a separate note, I noticed the following in your code:
Income / .SD[Nation == "America", Income]
.SD wonderful that this is a wonderful shorthand. However, to call it without the need to use all the columns that it encapsulates, you need to burden your code with additional memory costs. If you use only one column, consider naming this column explicitly, or perhaps add the .SDcols argument (after j ) and name the columns you .SDcols .
source share