2

output what i am getting in the dataframe

col1 col2 col3 col4
abc        25    35
abc  asd   25    45
def        15    36
erf        23    69
erf  asd   25    36
erf  dfg   85    78

Convert like this

 1. col1 col2 col3 col4  

 2.  
 3. abc        25    35 
 4. abc  asd   25    45 
 5. abc  def   15    36
 6.  
 7. def erf   23    69 
 8.
 8. erf asd   25    36
 9. erf dfg   85    78 
 10 erf fgh   78    89

I need a blank observation at 2 6 and 8. Is there any option?

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Jaikumar S
  • 144
  • 9

1 Answers1

2

If we assume that col1 and col2 are of class character, a quick solution would be

res <- do.call(rbind, lapply(split(df, df$col1), function(x) rbind("", x)))
row.names(res) <- NULL
res
#   col1 col2 col3 col4
# 1                    
# 2  abc        25   35
# 3  abc  asd   25   45
# 4                    
# 5  def        15   36
# 6                    
# 7  erf        23   69
# 8  erf  asd   25   36
# 9  erf  dfg   85   78

Or using data.table package (which doesn't assume character class necessarily)

library(data.table)
setDT(df)[df[, c(NA, .I), by = col1]$V1]
#    col1 col2 col3 col4
# 1:   NA   NA   NA   NA
# 2:  abc        25   35
# 3:  abc  asd   25   45
# 4:   NA   NA   NA   NA
# 5:  def        15   36
# 6:   NA   NA   NA   NA
# 7:  erf        23   69
# 8:  erf  asd   25   36
# 9:  erf  dfg   85   78
David Arenburg
  • 91,361
  • 17
  • 137
  • 196