Given the data frame below:
df <- data.frame(v1 = c(3, 0, 5, 1, 0),
v2 = c(2, 0, 0, 0, 0),
v3 = c(0, 0, 3, 0, 0),
v4 = c(0, 0, 0, 2, 0),
v5 = c(0, 0, 0, 0, 0),
v6 = c(0, 0, 0, 0, 7))
df
v1 v2 v3 v4 v5 v6
1 3 2 0 0 0 0
2 0 0 0 0 0 0
3 5 0 3 0 0 0
4 1 0 0 2 0 0
5 0 0 0 0 0 7
The desired result is the following data frame:
v1 v2 v3 v4 v5 v6
1 3 2 NA NA NA NA
2 NA NA NA NA NA NA
3 5 0 3 NA NA NA
4 1 0 0 2 NA NA
5 0 0 0 0 0 7
I'd like to replace all consecutive zeros in each row with NA under the condition that, looking at each row from left to right, there exists no non-zero number further down the row.
I've written a for loop to achieve this result, but this is really slow for a larger data frame:
for(i in 1:nrow(df)) {
for (j in 1:ncol(df)){
if ((df[i,j] == 0) & (apply(df[j:ncol(df)], 1, sum)[i] == 0)){
df[i,j] <- NA
}
}
}
I'd like a more efficient solution.