I have a matrix, and some cells are equal to 0. What I want to do is giving to these cells the same value from the cell which stays in the same row, but in the column before that.
I solved this problem with two for-loops, but as you know my solution is too slow because of nested for-loops.
Here is my little matrix, I gave to some cells 0 to show how my matrix looks like.
set.seed(1)
df <- matrix(data = rnorm(n = 20, mean = 0, sd = 1), nrow = 5, ncol=4)
df[1,2] <- 0
df[1,3] <- 0
df[2,3] <- 0
df[3,4] <- 0
and it is the solution that I found,
for(i in (1 : nrow(df))){
for(j in (2 : ncol(df))){
if (df[i,j] == 0){
df[i,j] <- df[i,j-1]
}
}
}
I would be very thankful, if somebody can find a more effective solution than I found.