Go back to Home

Inserting rows to data frame at any position [R]

While I was carring out a text analysis, a was stuck at a point where I had to insert multiple rows to a dataframe at different indexes. Though this seems to be easy I couldn't find any solution to this online.

So a little backstory, I have a dataframe with title of abstract in each row. Now I wanted to add author names after each title row which is stored as a list .The number of authors may vary.

Screen Shot 2019-01-19 at 4.06.47 PM

This is the author list with with 209 elements and each element has names of different authors who contributed to that abstract.

Let me show you how I did this.

I used tibble package. Its a package for data.frame manipulation.

library(tibble)

add_row() is a builtin function of tibble package that lets you add one row after/before an index.

Now for this purpose, I used a nested for loop. first for loop will iterate from 1 to the length of the author list (1:209).

for (each in 1:length(insert_count$charac_count)) {

}

The second for loop will iterate over the count of elements in each row of the list.For example first row of the list has 4 author names. So the Iteration will be from 1 to 4.

  for (in_row in 1:(insert_count$charac_count[each])) {
    
  }

Now inside this nested for loop is the add_row() function.

author_insti<-add_row(author_insti,.after = which(author_insti$s.no==each))

author_insti is the data.frame to which I want to add rows to. .after = is used to define the index after which i want to add rows. I used which() function to define the position based on the serial number"s.no" of the rows. The reason I did this because the index of the rows change after row insertion and if I had used just the index the rows would have been inserted at the same position and would have been a series of empty rows at the begining.

The whole code

for (each in 1:length(insert_count$charac_count)) {
  
  for (in_row in 1:(insert_count$charac_count[each]-1)) {
    author_insti<-add_row(author_insti,.after = which(author_insti$s.no==each))
  }
  
}

and viola! This is how it looks after inserting rows

Screen Shot 2019-01-16 at 11.36.35 PM

now just use simple replacement to add values to these rows.

Same thing can be done to insert columns by using add_column() function