gpt4 book ai didi

R//如果满足 data.table 的其他列中的多个条件,则计算行数并求和 col 值//高效且快速的 data.table 解决方案

转载 作者:行者123 更新时间:2023-12-04 10:28:34 24 4
gpt4 key购买 nike

我有一个大数据表(~41 Mio.rows * 20+ col)并且想要根据数据表的其他行中的结果进行逐行计算。具体来说,我想进行计算。
(1)计算特定ID(col ID)在每次购买交易(时间戳)时进行的销售交易次数(from_ID中的ID)
(2)一个ID在每次购买交易(col ID)时所做的总销量(col Value//from_ID)的总和

我有一个有效的解决方案,但它非常低效且缓慢。我想知道是否有更快/更有效(可能)基于 data.table 的问题解决方案。

这是我的可重现示例,我要计算的列是“先前销售额”和“先前销售额”:

数据

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)

最佳答案

在基础 R 中,您可以执行此操作。

data_sample <- cbind(data_sample, t(apply(data_sample, 1, function(x) {
r <- data_sample[data_sample$from_ID == x[["ID"]] &
data_sample$timestamp < x[["timestamp"]], ]
c(x1=NROW(r), x2=sum(r$Value))
})))

data_sample
# timestamp ID from_ID Value x1 x2
# 1 2018-04-04 00:39:02 1 4 100 0 0
# 2 2018-06-04 00:50:22 1 5 150 0 0
# 3 2018-09-04 03:07:29 1 4 50 2 150
# 4 2018-12-04 02:15:57 1 8 200 3 300
# 5 2018-08-04 02:15:57 10 1 50 0 0
# 6 2018-09-04 02:15:57 9 1 100 0 0
# 7 2018-10-04 02:15:57 8 1 150 0 0
# 8 2018-12-20 02:15:57 7 1 40 0 0

关于R//如果满足 data.table 的其他列中的多个条件,则计算行数并求和 col 值//高效且快速的 data.table 解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60526761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com