我有一个for循环,我希望它与R并行运行。下面的循环使用index m遍历数据库中的每个产品(我总共有M种产品要定价)。我将原始价格(这是一个数字)和从列表中读取的折扣率作为输入传递给我的定价函数(所以我必须使用[[]] formulation提取这个值。
for(m in 1:M)
{
myList[paste0("Product", m)] <- list(priceProduct(originalPrice, discounts[[m]]))
}这个循环运行得很好,最后我得到了包含每个产品的正确折扣价格的列表myList。myList拥有名为ProductX的所有元素,其中X是我的原始数据库中的产品位置(在循环中是计数器m)。唯一的问题是它的运行速度非常慢,所以我想知道如何将其并行化。有什么建议吗?
发布于 2015-05-30 08:11:20
在你担心并行处理之前,首先要对你的代码进行矢量化。R代码通常是矢量化的,但并行处理仍然有更多的工作要做。foreach和Rcpp (如果您知道C++)包还可以使事情变得更加快捷。或者你可以和Julia碰碰运气,虽然不是很成熟,但速度很快。然而,对于大多数日常工作,矢量化做到了这一点。
您的问题的答案有点取决于数据和函数的结构细节。下面做了一些松散的假设,但您应该能够根据您的具体情况进行调整。(或者只是添加更多细节,我会回来编辑的。)
# Let's say:
m <- 100
# `paste` functions can accept a sequence, and are easy to vectorize
product <- paste0("Product", 1:m)
# Let's chuck everything in a `data.frame` to stay organized:
data <- data.frame(product, originalPrice, discount)
# If `priceProduct` accepts vector arguments:
data$salePrice <- priceProduct(data$originalPrice, data$discount)
# If not:
data$salePrice <- sapply(seq(1, nrow(data)), function(x){
priceProduct(data$originalPrice[x], data$discounts[x])
})
# If it spits out a list, more cleaning is in order:
data$salePrice <- do.call(c,
sapply(seq(1, nrow(data)), function(x){
priceProduct(data$originalPrice[x], data$discounts[x])
}))https://stackoverflow.com/questions/30540118
复制相似问题