【发布时间】:2017-12-07 06:11:58
【问题描述】:
以下代码的目标是对具有 400 列和 6000 行的数据集执行递归和迭代分析。在移动到所有可能的组合之前,它一次需要两列并对其执行分析。
正在使用的大数据集的小子集:
data1 data2 data3 data4
-0.710003 -0.714271 -0.709946 -0.713645
-0.710458 -0.715011 -0.710117 -0.714157
-0.71071 -0.714048 -0.710235 -0.713515
-0.710255 -0.713991 -0.709722 -0.71397
-0.710585 -0.714491 -0.710223 -0.713885
-0.710414 -0.714092 -0.710166 -0.71434
-0.711255 -0.714116 -0.70945 -0.714173
-0.71097 -0.714059 -0.70928 -0.714059
-0.710343 -0.714576 -0.709338 -0.713644
代码使用apply():
# Function
analysisFunc <- function () {
# Fetch next data to be compared
nextColumn <<- currentColumn + 1
while (nextColumn <= ncol(Data)){
# Fetch the two columns on which to perform analysis
c1 <- Data[, currentColumn]
c2 <- Data[, nextColumn]
# Create linear model
linearModel <- lm(c1 ~ c2)
# Capture model data from summary
modelData <- summary(linearModel)
# Residuals
residualData <- t(t(modelData$residuals))
# Keep on appending data
linearData <<- cbind(linearData, residualData)
# Fetch next column
nextColumn <<- nextColumn + 1
}
# Increment the counter
currentColumn <<- currentColumn + 1
}
# Apply on function
apply(Data, 2, function(x) analysisFunc ())
我认为apply() 将帮助我优化代码,而不是使用循环。不过,似乎没有什么大的影响。运行时间超过两个小时。
有人认为,apply() 的使用方式有问题吗?在apply() 呼叫中使用while() 不是一个好主意吗?还有其他方法可以改进此代码吗?
这是我第一次使用函数式编程。请告诉我您的建议,谢谢。
【问题讨论】:
-
data.table可能值得研究。 -
看看你的previous questions,他们似乎都在“改进循环”。我认为您以错误的方式处理此问题。我认为您最好详细说明您的总体目标是什么,以及您正在使用的数据示例。
-
@SymbolixAU - 是的。我一次取两列,然后在上面做
lm()。这为我想要捕获的每一行(每列的两个数据点)提供了$residuals。然后,我对数据集中每个可能的列组合重复此操作。 -
问题可能是因为函数内的循环导致瓶颈。因此,即使您使用 apply,它仍然会循环。为什么不列出所有可能的列(变量)组合,然后在应用构造中使用该列表(可能是 sapply 或 lapply)。
-
@ChetanArvindPatil 一切都好。它实际上与 Parfait 答案具有相同的逻辑——这基本上摆脱了循环。此外,您可能还想考虑使用 microsoft R。我发现它更快,尤其是在进行贝叶斯采样时。
标签: r performance optimization functional-programming