Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all columns plus an additional expression

Tags:

r

data.table

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.

like image 643
Dean MacGregor Avatar asked Mar 14 '26 02:03

Dean MacGregor


1 Answers

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

  • the return value should be a list (of columns);
  • .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 j returns a list, each element of the list becomes a column in the resulting data.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.

like image 100
Frank Avatar answered Mar 15 '26 17:03

Frank



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!