I have a data frame which has a column that is as follows:
[1] i5olv
[2]
[3] udp3o
[4]
[5]
[6]
[7] uem5i
[8] b0047
[9]
[10]
Notice that the elements have no specific order and there may be a variable number of empty rows between non-empty elements. I would like the column to look like this instead:
[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 a vectorized way? I can do this using a for-loop which caches the last non-empty value but this is slow.
An 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
df1 <- structure(list(Col1 = c("i5olv", "", "udp3o", "", "", "",
"uem5i",
"b0047", "", "")), .Names = "Col1", row.names = c(NA, -10L),
class = "data.frame")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With