1

I have some zero values and would like to replace by the previous value in R.

X var : 1 3 6 0 7 8 0 0 9 8 9 0 0 0 4 7 2 4

X new var : 1 3 6 6 7 8 8 8 9 8 9 9 9 9 4 7 2 4

sanyassh
  • 8,100
  • 13
  • 36
  • 70
Minh Pham
  • 13
  • 3

1 Answers1

2

You can use the dplyr and tidyr packages.

library(dplyr)
library(tidyr)

df <- data.frame(var = c(1,2,3,0,7,8,0,0,9,8,9,0,0,0,4,7,2,4))
df <- df %>% 
  dplyr::mutate(var = ifelse(var == 0, NA, var)) %>% 
  tidyr::fill(var, .direction = c("down"))
df  
> df
   var
1    1
2    2
3    3
4    3
5    7
6    8
7    8
8    8
9    9
10   8
11   9
12   9
13   9
14   9
15   4
16   7
17   2
18   4

Fill NA row with previous value iteratively in R

bbiasi
  • 1,549
  • 2
  • 15
  • 31
  • Oh, Thanks, i really appreciate your answer with all the code. – Minh Pham May 16 '19 at 19:25
  • @Minh Pham, please, Could you accept my answer?. Look at this. https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – bbiasi May 16 '19 at 19:28