我想把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化的(或C++化的(。每当在R或Python中看到索引和索引增量时,在99%的情况下,R或Python中有更好的表达式。
例如,在这种情况下,您实际上使用while循环来执行nld
,这是不好的。
在R中,您将使用Map()
,它可以通过向量/列表并行迭代。
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)