You can calculate the product of two subsets within a data.table in-line by using the prod()
function and subsetting the data with the i
parameter. Here is an example:
library(data.table) # create example data.table dt <- data.table(x = c(1, 2, 3, 4, 5), y = c(6, 7, 8, 9, 10)) # calculate product of subsets dt[, prod(x[i <= 3] * y[i > 3])] # output: [1] 1980
In this example, we are first subsetting x
with i <= 3
and y
with i > 3
, and then calculating the product of this subset using the prod()
function. We are doing this in-line by using the [ ]
operator to define the calculation within the data.table. The output of this calculation is 1980.
Asked: 2022-09-08 11:00:00 +0000
Seen: 9 times
Last updated: Dec 13 '21