Ask Your Question
3

How can I calculate the product of two subsets within a data.table in-line?

asked 2022-09-08 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-12-13 15:00:00 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-08 11:00:00 +0000

Seen: 9 times

Last updated: Dec 13 '21