如何矢量化 R 中 while 循环创建的输出?

How to vectorize the output created by a while loop in R?

我想从 while 循环中获取结果作为向量。我的代码看起来像这样,nld 只是一些数字数据,lk 代表一个国家/地区的年利率:

 i<-1
  while (i<=length(nld)) {
    lk<-((nld[i+1]-nld[i])/nld[i])*100
    i <- i+1
    print(lk)   }

但输出看起来像这样:

> [1] 2.34391
[1] 4.421947
[1] 0.6444809
[1] 11.29308
[1] 4.282817
[1] 1.773046
[1] 5.443044
[1] 6.332272
[1] 9.207917
[1] 6.173719
[1] 5.449088
[1] 3.977678
[1] 7.697896
[1] 6.313985
[1] 1.449447
[1] 5.149968
[1] 1.840442
[1] 2.628424
[1] 2.269874
[1] 4.195588
[1] -2.868499
[1] -2.764851
[1] 0.216549
[1] 1.907869
[1] -2.13202
[1] 4.637701
[1] 1.051423
[1] 3.946669
[1] 4.332345
[1] 6.260946
[1] 3.113528
[1] 1.537622
[1] 3.075729
[1] 2.925915
[1] 5.146445
[1] 6.129935
[1] 5.185049
[1] 3.45909
[1] 7.835161
[1] 9.649116
[1] 1.311721
[1] 0.3325002

...等等

而且我无法从这个循环中获取和绘制这些结果。如果有人能启发我,我将不胜感激。 提前致谢。

i <- 1
result <- c()
while (i<=length(nld)) {
    lk<-((nld[i+1]-nld[i])/nld[i])*100
    i <- i+1
    result <- c(result, lk)   } # this collects `lk`  in the vector `result`.

但是你正在做的是非常 C-ish(或 C++-ish)。 每当在 R 或 Python 中看到索引和索引递增时, 在 99% 的情况下,R 或 Python.

中有更好的表达

例如在这种情况下,您实际上是在使用 while 循环执行 nld - 这并不好。

在 R 中,您将使用 Map() - 它可以通过 vectors/lists.

并行迭代
nld <- 1:10
result <- Map(f=function(x, y) (x - y)/y * 100,
              nld[2:length(nld)],
              nld)

但是你的原代码有错误。 您从 i=1 循环到 i=length(nld) 但需要 nld[i+1]i+1 在最后一种情况下会要求某事不存在。 所以应该是 while (i < length(nld)) { ...

result <- Map(f=function(x, y) (x - y)/y * 100,
              nld[2:length(nld)],
              nld[1:(length(nld)-1)])

或者更像 R-ish:使用矢量化:

f <- function(x, y) (x-y)/y*100
> f(nld[2:length(nld)], nld[1:(length(nld)-1)])
## [1] 100.00000  50.00000  33.33333  25.00000  20.00000  16.66667  14.28571
## [8]  12.50000  11.11111

或:

f <- function(vec) {
  vec1 <- vec[2:length(vec)]
  vec2 <- vec[1:(length(vec)-1)]
  (vec1 - vec2)/vec1 * 100 # this uses vectorization!
}

f(nld)