Question

I have this data frame:

 A <- c(10, 20, 30, 40, 5)
 B <- c(5, 0, 0, 0, 0)
 df = data.frame(A, B)

And I want to replace the 0's in B with the sum of A and B[i-1]. I have searched everywhere, but I feel like I am missing something really basic. This is my desired result:

    A B
 1 10 5
 2 20 25
 3 30 55
 4 40 95
 5  5 100

I have tried this, but it didn't work:

 for(i in 2:length(df)){
 df$B <- A[i] + B[i-1]
 }

In Excel, this would be something like B$2 = A$2 + B$1. I cannot figure out how to do this in R. Any help would be greatly appreciated since I feel like I am missing something basic. Thanks!

Was it helpful?

Solution

You were very close. Try this:

for(i in 2:nrow(df)){
 df$B[i] <- df$A[i] + df$B[i-1]
 }

And to expand to those comments, could something like this work?

for(i in 2:nrow(df)){
 if((df$A[i] + df$B[i-1]) > 60) df$B[i] <- df$B[i-1] else{
  df$B[i] <- df$A[i] + df$B[i-1]}
 }

OTHER TIPS

# Data 
# I changed one of the later values of B to non-zero to confirm that only
# the zero values of B were getting changed

A <- c(10, 20, 30, 40, 5)
B <- c(5, 0, 0, 10, 0)
(df = data.frame(A, B))
#   A  B
# 1 10  5
# 2 20  0
# 3 30  0
# 4 40  0
# 5  5  10


for(i in 2:nrow(df)) {
    if(df$B[i]==0) df$B[i] <- df$A[i] + df$B[i-1]
        if(df$B[i] >= 60) df$B[i] <- df$B[i-1] 
  }

df
#   A  B
# 1 10  5
# 2 20 25
# 3 30 55
# 4 40 55
# 5  5 10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top