Add New Row at Specific Index Position to Dataframe in R
In this article, we will discuss how to add a new row at a specific index in the dataframe in the R programming language.
The main task here is to shift other rows and make space in the dataframe for the new row and then insert its contents. This can be done in two ways
Method 1: Using rbind()
rbind() function in R Language is used to combine specified Vector, Matrix, or Data Frame by rows.
Syntax: rbind(x1, x2, …, deparse.level = 1)
- x1, x2: vector, matrix, data frames
- deparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
Method 2: Using seq()
Another approach of doing the same is to use seq() function. Here the approach is the same, but the method is somewhat different. We are accessing rows of the dataframe and creating the space in it. Also, we used nrows() to count the total number of rows.
seq() function in R Language is used to create a sequence of elements in a Vector. It takes the length and difference between values as an optional argument.
Syntax: seq(from, to, by, length.out)
- from: Starting element of the sequence
- to: Ending element of the sequence
- by: Difference between the elements
- length.out: Maximum length of the vector