-1

I would like to add an empty row after each 8 rows in my whole dataset. The actual one is like :

original dataset

enter image description here

and the final result I would like to get is :

expected dataset

enter image description here

Thanks in advance.

user2100721
  • 3,557
  • 2
  • 20
  • 29
E.Bonf
  • 5
  • 1
  • 4
  • Why would you ever add a row like that to your data? Do you just want to change how the data is printed rather than actually adding bad observations to your data.frame? – MrFlick Jul 27 '16 at 15:27
  • Because I need that format to be exported into an excel file where every each 8 rows I add an empty one. Since I don't know how to do that in macro I thought that I could do that in R and then export the file into the xlsx format . – E.Bonf Jul 27 '16 at 15:30
  • 1
    But why do need that empty row? I can't think of a useful application for that. – Jaap Jul 27 '16 at 15:57
  • Because I wanna compute the mean of all the 8 micro_rate items for each ID. – E.Bonf Jul 27 '16 at 16:03
  • 2
    You can do that right in R instead of putting in an empty row. – Adam Jul 27 '16 at 16:13
  • Hi Adam, thanks for the tip. How would you do that? – E.Bonf Jul 27 '16 at 16:19
  • [See this Q&A](http://stackoverflow.com/questions/9723208/aggregate-multiple-variables-simultaneously) – Jaap Jul 27 '16 at 19:07

2 Answers2

0
cur <- rbind(df[1:8,], NA)
for(i in seq(from = 9, to = length(df), by = 8) {
    cur <- rbind(df[i:(i+7),], NA)
}
Adam
  • 648
  • 6
  • 18
0

This answer is for numeric columns.

Initially, for the first eight observations, you can generate a matrix that is a vector of ones with length 8 and an additional NA column: v<- c(rep(1, 8),NA)

and then you can kronecker product this matrix with the original: kron(a,v) (after applying as.matrix on both a and v).

this should be extendable for each 8th row using a loop.

For the character column, you can first separate it, rbind a NA row to each 8th element using a loop defined by seq and then cbind it back to the numeric matrix.