0

I am programming a script that takes some data, creates in a loop a new object named "newrow" as character, and adds the new row in an existing data.frame, using rbind()

while(i<=l) {      
      dir.process() #function that creates the object "newrow"
      marks<<-rbind(marks,newrow)
    }

The problem is that the loop works, but rbind() replaces the same row with the new data. I have only one row in my data frame, every time with the last data

How I can add new rows to the dataframe?

Thanks for all,

jfpalomeque.gonzalez

RHertel
  • 23,412
  • 5
  • 38
  • 64
jfpalomeque
  • 51
  • 1
  • 1
  • 4
  • Please provide a reproducible example: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – lukeA Jul 22 '15 at 09:47

1 Answers1

0

I created this function a while ago which does what you want.

#Christopher Barry, 28/01/2015

insertRows <- function(DF, #original data frame
                       mtx, #vector or matrix to insert
                       row){ #row at which to insert
  if(is.vector(mtx)){
    mtx <- matrix(mtx, 1, length(mtx), byrow=T)
  }
  nrows <- nrow(mtx)
  if(nrow(DF) >= row){
    DF[seq(row+nrows,nrow(DF)+nrows),] <- DF[seq(row,nrow(DF)),]
    DF[row:(row+nrows-1),] <- mtx
  }else{
    DF[seq(nrow(DF)+1,nrow(DF)+nrows),] <- mtx
  }
  return (DF)
}

It can also add several rows at a time lumped as a matrix.

I'm not sure why yours doesn't work. I can't see what i refers to in your loop.

CJB
  • 1,759
  • 17
  • 26
  • No, doesn't works. Abour `i`, the function `dir.process()` processes all the files of an directory listed in a object, wich long is `l`. When finish the process, `dir.process()` add `+1` of `i`. – jfpalomeque Jul 22 '15 at 11:02
  • Are you sure your function `dir.process()` is programmed to [change global variables](http://stackoverflow.com/questions/10904124/global-and-local-variables-in-r)? My function does insert rows to a data frame, but `mtx` must have either the length or number of columns equal to `ncol(df)` or depending on whether it's a matrix or vector. It works in my usage. Perhaps I've misunderstood what you are asking. – CJB Jul 22 '15 at 11:21
  • Totally, all the variables are globals `<<-´. I only want to add in every loop a new row with the data of ´newrow´. – jfpalomeque Jul 22 '15 at 11:26
  • Well your code seems correct to me. Without knowing what's in `dir.process` I can't help you further. – CJB Jul 22 '15 at 11:46
  • ´dir.process<-function(){ B<<-NA compute.A() compute.C() compute.D() compute.E() newrow<<-c(A, B, C, D, E) i<<-i+1 }´ – jfpalomeque Jul 22 '15 at 12:31