Fill blank lines with duplicates of the previous non-empty line

I have a data frame that has a column that looks like this:

[1] i5olv
[2]
[3] udp3o
[4]
[5]
[6]
[7] uem5i
[8] b0047
[9]
[10]

Note that the elements do not have a specific order and there may be a variable number of empty lines between non-empty elements. I would like the column to look like this:

[1] i5olv
[2] i5olv
[3] udp3o
[4] udp3o
[5] udp3o
[6] udp3o
[7] uem5i
[8] b0047
[9] b0047
[10] b0047

How can I do this in vector form? I can do this using a for-loop that caches the last non-empty value, but it is slow.

+4
source share
1 answer

Option using data.table

library(data.table)
setDT(df1)[, Col1:=Col1[1L] ,cumsum(Col1!='')]

 #    Col1
 #1: i5olv
 #2: i5olv
 #3: udp3o
 #4: udp3o
 #5: udp3o
 #6: udp3o
 #7: uem5i
 #8: b0047
 #9: b0047
 #10: b0047

data

 df1 <- structure(list(Col1 = c("i5olv", "", "udp3o", "", "", "", 
 "uem5i", 
 "b0047", "", "")), .Names = "Col1", row.names = c(NA, -10L),
  class = "data.frame")
+2
source

All Articles