如何用给定的步长填充包含数字序列的for循环中的向量?
我有以下代码:如何用给定的步长填充包含数字序列的for循环中的向量?,r,loops,vector,R,Loops,Vector,我有以下代码: library(dplyr) Q = 10000 span = 1995:2016 time = rep(span,times = Q, each= Q) id = rep(1:Q,times=length(span)) s1 = rep(rnorm(Q,0,1),times=length(span)) gdp = rep(rnorm(Q,0,1),times=length(span)) e = rep(rnorm(Q,0,1),times=length(span)) dfA
library(dplyr)
Q = 10000
span = 1995:2016
time = rep(span,times = Q, each= Q)
id = rep(1:Q,times=length(span))
s1 = rep(rnorm(Q,0,1),times=length(span))
gdp = rep(rnorm(Q,0,1),times=length(span))
e = rep(rnorm(Q,0,1),times=length(span))
dfA = data.frame(id,time,s1,e,gdp)
mgr = double()
stp = 10
for(K in seq(10,Q,stp)){
gr = double()
for(t in span){
wt1 = dfA %>% filter(time == t-1) %>%
arrange(desc(s1)) %>% mutate(w= s1/gdp)
zt1 = dfA %>% filter(time == t-1) %>% mutate(z1 = log(s1/e))
zt = dfA %>% filter(time == t) %>% mutate(z = log(s1/e))
gt = left_join(zt1,zt,by="name") %>%
mutate(g = z-z1) %>% select(name,g) %>% na.omit()
a = left_join(wt1,gt,by="name") %>% na.omit()
a = a %>% mutate(id = 1:length(a$name)) %>%
filter(id <= Q) %>% mutate(gbar = mean(g)) %>%
filter(id <= K) %>% mutate(sck = g-gbar,
gamma = w*sck)
gr = append(gr, sum(a$gamma))
}
mgr = append(mgr,mean(gr))
}
其中,dfA是包含id变量和时间变量等的数据帧。由于时间变量的范围是从1995年到2016年,并且K是步骤10的序列,因此我分别求助于append to store gr和mgr。问题是计算时间太长
所以我的问题是:有没有办法避免使用append来填充向量gr和mgr,从而减少计算代码所花费的时间?您可以使用设置的长度来初始化“gr”和“mgr”向量,而不是将它们作为一个双精度向量来初始化,并让R在每次迭代中扩展它们。优点是向量的内存是预先分配的,您不必重新定义整个变量mgr/gr
## initiate vectors with set length
mgr <- double(length = length(seq(10,Q,stp)))
gr <- double(length = length(1995:2016))
# fill the positions in each iteration
outerIteration <- (K - 10) / stp
innerIteration <- t - 1994
gr[innerIteration] <- sum(a$gamma)
# take the mean for each block of length 21 (2016 - 1995)
mgr[outerIteration] <- mean(gr[(outerIteraion -1)*21 + 1 : outerIteration*21])
样本数据将非常棒。请看:,和。谢谢您的回复。这就是我要找的。但是,它似乎并没有显著缩短运行时间。嵌套for循环的运行时间很长。您可以尝试只执行内部循环,然后尝试将df分组并执行最后一个过滤器