cloudscomputes
cloudscomputes

Reputation: 1484

R write data.table instruction in functional form/call

So if I want to get a data.table:DT's customer num sum by category mall_name, I can use:

DT[,sum(customer_num),by = mall_name]

But in some cases,like I want to apply/lapply this summary to a list of DT, I need the functional form of this compact form: I guess it would be:

`[.data.table`(DT,,sum(customer_num),by = mall_name)

how ever, this gave me a error:

Error: could not find function "[.data.table"

Is there anyone know how to write the functional form of it?

Upvotes: 2

Views: 110

Answers (1)

JAD
JAD

Reputation: 2170

As MichaelChirico noted, if you just use

`[`(dt, ...)

this should automatically use the correct option.

As an alternative, the actual function can be found using:

data.table:::`[.data.table`()

and used as follows:

library(data.table)

dt <- data.table(x = 1:5)

listOfDts <- lapply(1:5, function(x)copy(dt))

lapply(listOfDts, function(y) data.table:::`[.data.table`(y, , x := rep(1, 5)))

listOfDts

However, be aware of the risks involved using ::: to access a library's unexported objects. These may change without notice, since they are not exported, and thus not bound to any promised functionality.

An alternative approach to using the functional version of [ would be:

dt <- data.table(x = 1:5)

listOfDts <- lapply(1:5, function(x)copy(dt))

lapply(listOfDts, function(y) y[, x := 1])

Upvotes: 2

Related Questions