0

I would like to add 4 extra rows of NA after each row of data in a csv file.

I tried the following but it only adds 4 extra rows at the end of the csv file instead of after each row.

addrowdata<-read.csv('test.csv')
addrowdata[nrow(addrowdata)+4,] <- NA

This seems like something that should be quite easy to do but I am struggling. Does anyone have any ideas?

This is my first time posting, so I hope this is ok and sorry for any mistakes. I searched for this but couldn't find an answer.

rq55
  • 1
  • 1
    Have a look here for several options you can try: https://stackoverflow.com/questions/16453452/how-can-i-add-rows-to-an-r-data-frame-every-other-row – Tim Biegeleisen Jan 07 '18 at 14:49
  • Try to build a vector with this structure: `1,NA,NA,NA,NA,2,NA,NA,NA,NA...` (i.e. a vector with a sequence ranging from 1 to the number of rows of your data each followed by 4 NAs) and then use that vector to subset the data (with `data[v,]`, where `v` is the above vector). – nicola Jan 07 '18 at 15:00

1 Answers1

2

1) rbind/by Use rbind like this where DF is the input data frame:

do.call("rbind", by(DF, 1:nrow(DF), rbind, NA, NA, NA, NA))

or if the number of NAs is to depend on k then:

k <- 4
do.call("rbind", do.call("by", c(list(DF, 1:nrow(DF), rbind), as.list(rep(NA, k)))))

2) rbind/indexing Another way to use rbind would be;

DF[c(rbind(1:nrow(DF), NA, NA, NA, NA)), ]

or if the number of NAs is to depend on k then:

k <- 4
DF[do.call("rbind", c(list(1:nrow(DF)), as.list(rep(NA, k)))), ]

3) kronecker If DF were all numeric it could be converted to a matrix and the kronecker product taken giving the following matrix:

as.matrix(DF) %x% c(1, NA, NA, NA, NA)

or if the number of NAs is to depend on k then:

k <- 4
as.matrix(DF) %x% c(1, rep(NA, k))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thank you! rbind works perfectly! I've upvoted your answer but my low reputation doesn't allow it to show. This is a great solution and solved my problem. – rq55 Jan 07 '18 at 15:55
  • @rq55: Your low rep does not prevent you from accepting that answer. – IRTFM Jan 07 '18 at 21:22