gpt4 book ai didi

r - 在 R 中迭代多个条件时如何提高性能?

转载 作者:行者123 更新时间:2023-12-02 06:52:53 26 4
gpt4 key购买 nike

假设我有一个具有以下结构的数据集:

  • 我有N个产品
  • 我在 N 个国家开展业务
  • 我有N个支付伙伴
  • 可能的数据集包含 N 天
  • 我有 N 个不同的价格供客户选择

例如:

customer.id <- c(1,2,3,4,5,6,7,8)
product <- c("product1","product2","product1","product2","product1","product2","product1","product2")
country <- c("country1","country2","country1","country2","country1","country2","country1","country2")
payment.partner <- c("pp1","pp2","pp1","pp2","pp1","pp2","pp1","pp2")
day <- c("day1","day2","day1","day2","day1","day2","day1","day2")
price <- c("price1","price2","price1","price2","price1","price2","price1","price2")

customer.data <- data.frame(customer.id,product,country,payment.partner,day,price)
customer.data <- data.table(customer.data)

假设我想从中生成一个聚合,例如,对每个组合执行预测算法。为此,我确定了每个条件的唯一项并按如下方式对其进行迭代:

unique.products <- droplevels(unique(customer.data[,product]))
unique.countries <- droplevels(unique(customer.data[,country]))
unique.payment.partners <- droplevels(unique(customer.data[,payment.partner]))
unique.days <- droplevels(unique(customer.data[,day]))
unique.prices <- droplevels(unique(customer.data[,price]))

for(i in seq_along(unique.products)){
temp.data1 <- customer.data[product==unique.products[[i]]]
for(j in seq_along(unique.countries)){
temp.data2 <- temp.data1[country==unique.countries[[j]]]
for(k in seq_along(unique.payment.partners)){
temp.data3 <- temp.data2[payment.partner==unique.payment.partners[[k]]]
for(l in seq_along(unique.days)){
temp.data4 <- temp.data3[day==unique.days[[l]]]
for(m in seq_along(unique.prices)){
temp.data5 <- temp.data4[price==unique.prices[[m]]]
if(nrow(temp.data5)!=0){
# do your calculations here
print(temp.data5)
}
}
}
}
}
}

一般来说,这种代码结构可以正常工作,但在应用包含 500 万行的真实数据时,它会变得非常烦人。我想 R 在速度和性能方面并不是最好的语言。当然,我过去使用过多核处理,或者试图直接从 Hive 或 MySQL DataWarehouse 中获取这样的聚合。使用其他语言(如 C++ 或 Python)也是一种选择。

然而,有时所有这些选项都是不可能的,这总是让我使用完全相同的处理结构。所以我很长一段时间都在想,从架构的角度来看,是否有更好、更快的解决方案,因为众所周知(并且在基准测试时也变得非常清楚)for 循环和频繁的数据子选择非常非常慢.

感谢所有评论、提示和可能的解决方案!

最佳答案

您应该阅读您正在使用的包的文档。数据包 data.table 提供了一些优秀的 introductory tutorials .

customer.data <- data.frame(customer.id,product,country,payment.partner,day,price)
library(data.table)
setDT(customer.data)
customer.data[,
print(customer.data[.I]), #don't do this, just refer to the columns you want to work on
by = .(product, country, payment.partner, day, price)]

当然,一般情况下,您不会在此处打印 data.table 子集,而是直接在特定列上工作。

关于r - 在 R 中迭代多个条件时如何提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140139/

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