Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill empty rows with duplicates of previous non-empty row [duplicate]

Tags:

r

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.

like image 581
ruser45381 Avatar asked Oct 31 '22 05:10

ruser45381


1 Answers

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

data

 df1 <- structure(list(Col1 = c("i5olv", "", "udp3o", "", "", "", 
 "uem5i", 
 "b0047", "", "")), .Names = "Col1", row.names = c(NA, -10L),
  class = "data.frame")
like image 180
akrun Avatar answered Nov 08 '22 06:11

akrun