【发布时间】:2012-01-02 13:14:02
【问题描述】:
这是一个更集中的问题,基于我在Vectorize/Speed up Code with Nested For Loops 提出的另一个问题
基本上,我想加快这段代码的执行速度。我正在考虑使用apply 系列函数之一。 apply 函数必须使用/执行以下操作:
输入:循环区域 1 到 10;向量 sed 和 borewidth 预先分配的维度填充了 NA
流程:在sed和borewidth的每一个中填充数据,以内部for循环中实现的方式实现
输出:sed 和 borewidth 向量
假设(h/t Simon Urbanek):每行的开始点和结束点是连续的、连续的,并且对于每个区域,从 0 开始。
代码如下:
for (region in 1:10) {
# subset standRef and sample by region code
standRef.region <- standRef[which(standRef$region == region),]
sample.region <- sample[which(sample$region == region),]
for (i in 1:nrow(sample.region))
{
# create a dataframe - locations - that includes:
# 1) those indices of standRef.region in which the value of the location column is greater than the value of the ith row of the begin column of sample.region
# 2) those indices of standRef.region in which the value of the location column is less than the value of the ith row of the finish column of sample.region
locations <- standRef.region[which((standRef.region$location > sample.region$begin[i]) & (standRef.region$location < sample.region$finish[i])),]
sed[end_tracker:(end_tracker + nrow(locations))] <- sample.region$sed[i]
borewidth[end_tracker:(end_tracker + nrow(locations))] <- sample.region$borewidth[i]
# update end_tracker to the number of locations rows for this iteration
end_tracker <- end_tracker + nrow(locations)
}
cat("Finished region", region,"\n")
}
borewidth 和sed 的样本数据。编辑:更正dput中的格式错误
structure(list(region = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
begin = c(0L, 2253252L, 7091077L, 9120205L, 0L, 135094L,
941813L, 5901391L, 6061324L), finish = c(2253252L, 7091077L,
9120205L, 17463033L, 135094L, 941813L, 5901391L, 6061324L,
7092402L), sed = c(3.31830840984048, 1.38014704208403, 6.13049140975458,
2.10349875097134, 0.48170587509345, 0.13058713509175, 9.13509713513509,
6.13047153058701, 3.81734081501503), borewidth = c(3L, 5L,
2L, 1L, 1L, 1L, 2L, 4L, 4L)), .Names = c("region", "begin",
"finish", "sed", "borewidth"), class = "data.frame", row.names = c(NA,
-9L))
TIA。
【问题讨论】:
-
split和lapply将有助于外循环。如果可能,您可能还想考虑merge-ing 2 个数据帧以在没有显式循环的情况下执行此操作。 -
一些(虚拟)数据会让我们更容易为您提供帮助。
-
@Thierry,一些示例数据。参考数据 -
standRef- 以dput格式在stackoverflow.com/questions/8691966/… 中提供。谢谢 -
@James 我尝试使用
sapply,将上面的代码放入函数foo1并从vecOfData <- sapply(vecOfData, function(x) foo1(1:10))调用它,其中vecOfData <- c(sed, borewidth)。然而,这似乎只是遍历sed和borewidth中的每个元素——超过一百万次迭代! -- 而不是将每个向量视为一个元素。我如何在上面的上下文中使用split?谢谢。 -
请给我们代码来生成可以通过简单的复制粘贴工作的数据集。 structure() 只生成一个 data.frame。那是sed还是borewidth?而且我们没有示例 data.frame(可能与 sample() 函数混淆)。
标签: r