-2

Hello in R how could I write a function which takes as an input a number at which aline should be entered into an existing object

matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)

Each vector should now be entered into the matrix into the matrix at row 3 (so it should be the new co row 3 . The other rows would just be a pushed so the old row 3 is row 4 then

NM Pennypacker
  • 6,704
  • 11
  • 36
  • 38
sdji
  • 1
  • 4

2 Answers2

0

Here's a function I wrote for that a while back. I've been using it.

#Christopher Barry, 28/01/2015

insertRows <- function(DF, mtx, row){
  if(is.vector(mtx)){
    mtx <- matrix(mtx, 1, length(mtx), byrow=T)
  }
  nrow0 <- nrow(DF)
  nrows <- nrow(mtx)
  ncols <- ncol(DF) #should be same as for mtx
  if(is.matrix(DF)){DF <- rbind(DF, matrix(0, nrows, ncols))}
  if(nrow0 >= row){
    DF[seq(row+nrows,nrow0+nrows),] <- DF[seq(row,nrow0),]
    DF[row:(row+nrows-1),] <- mtx
  }else{
    DF[seq(nrow0+1,nrow0+nrows),] <- mtx
  }
  return (DF)
}

Edited to work for matrices and data frames.

CJB
  • 1,759
  • 17
  • 26
0

One way of doing this can be :

aa<- matrix(rnorm(9),ncol=3,nrow=5)
x<-c(1,7,8)
rbind(aa[1:2,],x,aa[3:5,])

A similar solution ot this, actually: R: Insert a vector as a row in data.frame

Community
  • 1
  • 1
R.S.
  • 2,093
  • 14
  • 29