零之间的向量的累积和

时间:2018-09-17 19:38:12

标签: r break addition

我需要帮助。我想计算一个索引,将先前计算的值添加到下一个值,直到它为0,然后再从那里开始。

这是我尝试过的:

NIVtest <- NIV[1:35,1]
NIVtest <- data.frame(NIVtest)

test <- matrix(nrow=35,ncol=1)
test <- as.data.frame(test)
names(test) <- "NI"
test
test[1,1] <- 0

for(i in 1:35){

  NI = results[i,1]+NIVtest[i+1,1]
  test[i+1,1] <- NI[1]
}

以下是测试数据:

df <- data.frame(NIVtest = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13.5, 18.92, 28.98, 13.39, 9.24, 29.38, 55.25, 0, 15.86, 7.52, 0))

这是预期的结果:

c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13.5, 32.42, 61.4, 74.79, 84.03, 113.41, 168.66, 0, 15.86, 23.38, 0)

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

使用data.table的一种方法:

# load data.table
library(data.table)

# convert your dataframe (assuming it's named df) to a data.table
dt <- as.data.table(df)

# create a group id for each set of numbers between the zeros
dt[ , groupid := rleid(NIVtest==0)]

# create the desired index
dt[ , index := cumsum(NIVtest), by=groupid]

结果:

> dt[ , .(NIVtest, index)]
    NIVtest  index
 1:    0.00   0.00
 2:    0.00   0.00
 3:    0.00   0.00
 4:    0.00   0.00
 5:    0.00   0.00
 6:    0.00   0.00
 7:    0.00   0.00
 8:    0.00   0.00
 9:    0.00   0.00
10:    0.00   0.00
11:    0.00   0.00
12:    0.00   0.00
13:    0.00   0.00
14:    0.00   0.00
15:    0.00   0.00
16:    0.00   0.00
17:    0.00   0.00
18:    0.00   0.00
19:    0.00   0.00
20:    0.00   0.00
21:    0.00   0.00
22:    0.00   0.00
23:    0.00   0.00
24:    0.00   0.00
25:   13.50  13.50
26:   18.92  32.42
27:   28.98  61.40
28:   13.39  74.79
29:    9.24  84.03
30:   29.38 113.41
31:   55.25 168.66
32:    0.00   0.00
33:   15.86  15.86
34:    7.52  23.38
35:    0.00   0.00

答案 1 :(得分:0)

以下是循环执行的方法:

# your data
vec <- c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
         0, 0, 0, 0, 13.5, 18.92, 28.98, 13.39, 9.24, 29.38, 55.25, 0, 
         15.86, 7.52, 0)

n <- length(vec)

# empty vector to store results
result <- vector(length=n)

# loop time!
for(i in seq(n)) {
    if(vec[i]==0) {
        result[i] <- 0
    } else {
        result[i] <- result[i-1] + vec[i]
    }
}