R fulfill empty cells with previous values [closed]

Assuming that the first column contain blanks ("") and is character class, we convert the blanks to NA and use na.locf to replace the NA elements with the non-NA previous element, then paste the output with the second column and create a new column (“colN”).

library(zoo)
library(data.table)
setDT(df1)[col1=="", col1:= NA][, colN := as.numeric(paste0(na.locf(col1), col2))]
df1
#   col1 col2 colN
#1:    1    0   10
#2:   NA    2   12
#3:   NA    3   13
#4:    2    2   22
#5:   NA    0   20
#6:    3    4   34

Update

Noticed the at the OP edited the post with the changes made on the first column i.e. now the blanks ("") got mysteriously changed to na (which is not a true NA). In that case, while reading the dataset with read.csv/read.table, the na.strings = "na" can be used to automatically convert the “na” to NA or else

 setDT(df1)[col1=="na", col1 := NA][, colN := as.numeric(paste0(na.locf(col1, col2))]

data

df1 <- structure(list(col1 = c("1", "", "", "2", "", "3"), col2 = c(0L, 
2L, 3L, 2L, 0L, 4L)), .Names = c("col1", "col2"), row.names = c(NA, 
-6L), class = "data.frame")

Leave a Comment