很慢For,if if if语句在R中

MKW*_*lsh 2 for-loop if-statement r

我有一个非常大的桌子(n=2,723,860),我想从负风向(-180到180度)计算正风向(0到360度).

我的一个循环,一个带有嵌套if和else if语句的for循环,需要永远运行(见下文).

我是R的新手,我认为我没有这种结构有效.有关如何更好地构建它的任何帮助,以便它不需要这么长时间(目前在20分钟仍然没有完成)?

for (j in 1:n){
  if (Jun012015$D[j] < 0){
   Jun012015$D1[j] <- (Jun012015$D[j] * (-1))
  } else if (Jun012015$D[j] > 0){
      Jun012015$D1[j] <- ((Jun012015$D[j] * (-1)) + 360)
  } else {
      Jun012015$D1[j] <- 0
  }
}
Run Code Online (Sandbox Code Playgroud)

Das*_*son 7

我希望docendo discimus决定重新开放他们的答案,因为它很好.这是他们答案的代码(如果他们重新打开他们,我将删除)

idx1 <- Jun012015$D < 0
idx2 <- Jun012015$D > 0
idx3 <- Jun012015$D == 0

Jun012015$D1[idx1] <- Jun012015$D[idx1] * (-1)
Jun012015$D1[idx2] <- (Jun012015$D[idx2] * (-1)) + 360
Jun012015$D1[idx3] <- 0
Run Code Online (Sandbox Code Playgroud)

对于那些尚未掌握矢量化的人,我更喜欢这个答案.它的工作原理并不应该比我的慢得多(如下所示).但我认为它更清楚地显示了这个过程,并且可以在未来帮助OP更多,这可能只是对于仍在使用for循环和if语句的人来说看起来像个谜.但这是我的单行应该完成它:

Jun012015$D*(-1) + 360*(Jun012015$D > 0)
Run Code Online (Sandbox Code Playgroud)

你需要将它存储到变量中或用它覆盖Jun012015 $ D.