【问题标题】:How to remove the for loop and perform vectorization for data frame variables?如何删除 for 循环并对数据框变量执行矢量化?
【发布时间】: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


    【解决方案1】:

    如果计算速度不是您关心的问题并且您了解自己在做什么,那么 for 循环就可以了。它没有错。它可以通过矢量化提高效率,但这不是必需的。

    很难为您提供解决方案,因为该示例很难遵循并调用我不知道它在做什么的函数,但一般来说,如果您有一个取决于 i 的函数 f(i)可以转

    sum = 0
    for( i in 1:n) sum = sum + f(i)
    

    进入

    sum(sapply(1:n,function(i) f(i)))
    

    顺便说一句,调用变量 sum 是个坏主意,因为这也是 R 中常用函数的名称。

    【讨论】:

    • 谢谢罗希特。我用函数 multipleby2 sum = 0 > for( i in 1:5) sum = sum + multipleby2(i) R > sum R> [1] 30. 另一方面: R> sum(sapply(1:5,function(i) multipleby2(i))) R> [1] 30. 我现在可以相应地更改代码。无论如何,这个问题实际上暗示有时 for-inside-for 可能会阻止使用高级技术的需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多