samedi 26 janvier 2019

Fill select row above and below index value

I have a variable (X) in data frame (df) which looks like this

df$X
NA
12345
NA
NA
32409
NA
NA
NA
NA
NA
04598
NA
NA
NA

I need to do the following:

Where X is not NA, replace:
- the previous row in X with the value
- fill in the remainder of the rows until the next value is reached

Ultimately, it needs to look like this

df$X
12345
12345
12345
32409
32409
32409
32409
32409
32409
04598
04598
04598
04598
04598

I tried using a for loop to accomplish the first part (filling in the previous row) but can't seem to get this to work

for (x in df$X) {

x = df$X[x]  
y = x -1  
out$X2[y] <-  ifelse(!is.na(x), x, NA)

}

Your help much appreciated!

Aucun commentaire:

Enregistrer un commentaire