Let's say I start with
mtcarsDT<-data.table(mtcars)
and I want the equivalent of
mtcarsDT[,.(mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb, newcol=myFunc())]
but I just want to type something short like mtcarsDT[,.(.SD, newcol=myFunc()) but of course that syntax doesn't work.
My usual way is
c(.SD, .(newcol = f())
This approach is also useful when applying functions to multiple columns, like
c(
g = lapply(.SD, g),
f = lapply(.SD, f),
.(N = .N)
)
This syntax works because
.SD already is a list;c() can be used to combine lists; and .() is an alias for list() offered for convenience inside DT[...].Details. From ?data.table
As long as
jreturns alist, each element of the list becomes a column in the resultingdata.table. This is the default enhanced mode.
A similar line shows up twice in the first vignette, vignette("datatable-intro"), but unfortunately there are no examples like the OP's. (Maybe one should be added?)
I don't really want to create a column, I just want to view the result of the expression next to the existing columns without having to save the column and then delete it later
For this use case, the best solution would probably be taking a shallow copy. That functionality is not available yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With