【发布时间】:2018-02-01 09:40:58
【问题描述】:
我有一些分层数据,需要分别对每个层应用操作。我设法用一个 for 循环来做到这一点(见下面的例子)。但是,循环太慢了,因为我正在处理一个庞大的数据集。我相信必须有一种方法可以加快速度,例如使用apply 函数,但不幸的是我找不到更好的解决方案。
问题:如何提高此操作的速度?
# Some example data (do not care about the data creation, only the loop is important)
set.seed(123)
N <- 100
strata <- round(runif(N, 1, 1000)) # Strata
x1 <- rpois(N, lambda = 50) # Variable 1
x2 <- rpois(N, lambda = 50) # Variable 2
ind1 <- as.factor(rbinom(N, 1, 0.3)) # Group indicator 1
ind2 <- as.factor(rbinom(N, 1, 0.6)) # Group indicator 2
x1[ind1 == 0] <- 0
x2[ind1 == 0] <- 0
x1[ind2 == 0] <- 0
x2[ind2 == 1] <- 0
x1_sum <- sum(x1)
x2_sum <- sum(x2)
# # # # # The folowing loop is too slow # # # # #
new_values <- x2 # Apply the following operation strata by strata
for(i in 1:length(table(strata))) {
x1_sum_strata <- sum(x1[strata == as.numeric(names(table(strata)))[i]])
x2_sum_strata <- sum(x2[strata == as.numeric(names(table(strata)))[i]])
new_values[x1 == 0 & ind1 == 1 & strata == as.numeric(names(table(strata)))[i]] <-
(x1_sum / x2_sum) * (x1_sum_strata / x2_sum_strata)
}
【问题讨论】:
-
首先我不会一直计算
table(strata)...只需将结果存储在循环之前并使用它,例如:tbl <- table(strata)... 那么我认为您可以使用split(1:N,strata)获取具有相同值的层索引,并在不使用条件@ 的情况下将它们用于循环中的strata、x1和x2的子集987654329@ 每次(速度较慢,因为它一直在枚举所有向量) -
如果您只想在
strata == as.numeric(names(table(strata)))时进行更改,然后将其放入变量中并循环它..否?但是你能解释一下这个条件的含义吗? -
as.numeric(names(table(strata)))主要是一种复杂的表达方式unique(strata) -
感谢所有 cmets!似乎我低估了
as.numeric或table等函数需要多长时间。
标签: r performance for-loop