I have a large data table (~41 Mio. rows * 20+ col) and want to do a row-wise calculation conditioned on outcomes in other rows of the data table. Specifically, I want to make to calculations. (1) Calculate the number of sales transactions (ID in from_ID) a specific ID (col ID) has made at the time of each purchase transaction (timestamp) (2) the sum of total sales volume (col Value // from_ID) an ID has made at the time of each purchase transaction (col ID)
I have a solution that works, however it is quite inefficient and slow. I am wondering if there is a faster / more efficient (probably) data.table based solution to the problem.
Here is my reproducible example, the columns I want to calculate are "prior sales" and "prior sales amount":
Data
timestamp = c(
"2018-04-04 00:39:02", "2018-06-04 00:50:22", "2018-09-04 03:07:29",
"2018-12-04 02:15:57", "2018-08-04 02:15:57", "2018-09-04 02:15:57",
"2018-10-04 02:15:57", "2018-12-20 02:15:57"
)
ID = as.character(c(1,1,1,1,10,9,8,7))
from_ID = as.character(c(4,5,4,8,1,1,1,1))
Value = c(100,150,50,200,50,100,150,40)
data_sample = as.data.frame(cbind(timestamp, ID, from_ID,Value), stringsAsFactors = F)
data_sample$timestamp = as.POSIXct(data_sample$timestamp)
data_sample$Value = as.numeric(data_sample$Value)
# Approach
prior_sales = data.frame()
prior_sales_amount = data.frame()
for (i in 1:nrow(data_sample)) {
row = data_sample[i,]
sales = subset(data_sample, data_sample$from_ID == row$ID & data_sample$timestamp < row$timestamp)
prior_s = nrow(sales)
prior_sales = rbind(prior_sales, prior_s)
prior_s_a = ifelse(prior_s == 0, 0, sum(sales$Value))
prior_sales_amount = rbind(prior_sales_amount, prior_s_a)
}
data_sample = cbind(data_sample, prior_sales, prior_sales_amount)