Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a new row in specific place in a dataframe

Tags:

r

add

row

rbind

Heres my data:

 > data
  Manufacturers       Models
1   Audi                RS5  
2   BMW                 M3  
3   Cadillac            CTS-V  
4   Lexus               ISF

I would like to add 1 row in the fourth row, like this:

 > data
  Manufacturers       Models
1   Audi                RS5  
2   BMW                 M3  
3   Cadillac            CTS-V  
4   Benz                C63
5   Lexus               ISF

I have tried to use the rbind() like this:

 Benz = data.frame(Manufacturers = "Benz", Models = "C63")
 newdata = rbind(data,Benz)

But I cannot add to the place I want. I would appreciate any help on this question. Thanks a lot.

like image 470
Bruce Brown Avatar asked Apr 27 '13 08:04

Bruce Brown


2 Answers

In case you don't want the index but rather a one-off "quick fix" for some spreadsheet-like appearance, you might resort to

newData <- rbind( data[1:3,], Benz, data[ 4,] )
like image 78
vaettchen Avatar answered Oct 05 '22 08:10

vaettchen


this function would improve and solve your problem:

INSERT_NA_ROW <- function(indice, tabla) {
  new_Row <- NA
  long <- NROW(tabla)
  new_Data<- rbind(tabla[1:indice,], new_Row ,tabla[(indice + 1):(long),])
  return(new_Data)
} # Insert Row in index of dataframe

Thanks for read me!

like image 25
Sergio Mora Avatar answered Oct 05 '22 06:10

Sergio Mora