【发布时间】:2015-05-27 05:07:38
【问题描述】:
我有一个包含 6 个变量的数据框 (V6Stationary42Obs1D.df)。对于我的数据框的第一个变量,我获得如下值(effrectpl[i,1] 中的“1”表示我获得了第一个变量的值):
sum <- 0
for (i in as.integer(1:5)) { # 5= no. of variables - 1 = 6-1=5
sum <- sum + conditionalGb(as.matrix(V6Stationary42Obs1D.df[gctemplate(6,1,1)[effrectpl[i,1],]][(1+0):42,]), nx = 1, ny = 1, order = 5)[[2]]
}
sum
对于我的数据框的第二个变量,我获得如下值(effrectpl[i,2] 中的“2”表示我获得了第二个变量的值):
sum <- 0
for (i in as.integer(1:5)) {
sum <- sum + conditionalGb(as.matrix(V6Stationary42Obs1D.df[gctemplate(6,1,1)[effrectpl[i,2],]][(1+0):42,]), nx = 1, ny = 1, order = 5)[[2]]
} # "6" in gctemplate(6,1,1) is the no. of variables in the data frame
# there is no change other than the one in effrectpl[i,2] for the 2nd variable
sum
我的数据变量中有 6 个变量,我必须对每个变量执行相同的操作(当我将此质量转换为函数时,变量的数量会发生变化;值得注意的是,对于神经科学来说,有时可能有大约 300 个变量!并猜测计算负载)。我需要一个能够克服上述问题的矢量化解决方案。
我做了什么(想法):
sum <- c(0,0,0,0,0,0)
for (i in as.integer(1:5)) {
sum??? <- sum + ????
}
sum
虽然我知道 s/t/...apply 系列,但在这个特殊问题中,我也无法弄清楚如何处理它们。
任何帮助将不胜感激。提前谢谢。
注意:我找到了以下 for-inside-for 解决方案,现在,认为在上述情况下,矢量化解决方案可能是困难的或不必要的。无论如何,如果我看到某种非解决方案,我会很高兴。
for (j in as.integer(1:6)) {
sum[j] <- 0
for (i in as.integer(1:5)) {
sum[j] <- sum[j] + conditionalGb(as.matrix(V6Stationary42Obs1D.df[gctemplate(6,1,1)[effrectpl[i,j],]][(1+0):42,]), nx = 1, ny = 1, order = 5)[[2]]
}
print(sum[j])
}
【问题讨论】:
标签: r for-loop vectorization