Skip to content
Related Articles

Related Articles

Improve Article

How to insert blank row into dataframe in R ?

  • Last Updated : 04 Aug, 2021

In this article, we will discuss how to insert blank rows in dataframe in R Programming Language.

Method 1 : Using nrow() method 

The nrow() method in R is used to return the number of rows in a dataframe. A new row can be inserted at the end of the dataframe using the indexing technique. The new row is assigned a vector NA, in order to insert blank entries. The changes are made to the original dataframe. 

Syntax:

df [ nrow(df) + 1 , ] <- NA

Example:



R




# declaring a dataframe in R
data_frame <- data.frame(col1 = c(1:4),
                         col2 = letters[1:4],
                         col3 = c(8:11))
 
print ("Original DataDrame")
print (data_frame)
 
# calculating total rows
rows <- nrow(data_frame)
 
# inserting row at end
data_frame[rows+1,] <- NA
 
print ("Modified DataDrame")
print (data_frame)

Output

[1] "Original DataDrame"
 col1 col2 col3
1    1    a    8
2    2    b    9
3    3    c   10
4    4    d   11
[1] "Modified DataDrame"
 col1 col2 col3
1    1    a    8
2    2    b    9
3    3    c   10
4    4    d   11
5   NA <NA>   NA

Method 2 : Using insertrows() method

A package in R programming language “berryFunctions” can be invoked in order to work with converting the lists to data.frames and arrays, fit multiple functions. 

Syntax:

install.packages(“berryFunctions”)

The method insertRows() in R language can be used to append rows at the dataframe at any specified position. This method can also insert multiple rows into the dataframe. The new row is declared in the form of a vector. In the case of a blank row insertion, the new row is equivalent to NA. The changes have to be saved to the original dataframe. 

Syntax:

insertRows(df, r, new = NA)



Parameter : 

df – A dataframe to append row to

r – The position at which to insert the row

new – The new row vector to insert

Example:

R




library ("berryFunctions")
 
# declaring a dataframe in R
data_frame <- data.frame(col1 = c(1:4),
                         col2 = letters[1:4],
                         col3 = c(8:11))
 
print ("Original DataDrame")
print (data_frame)
 
# inserting row at end
data_frame <- insertRows(data_frame, 2 , new = NA)
 
print ("Modified DataFrame")
print (data_frame)

Output

[1] "Original DataDrame" 
col1 col2 col3 
1    1    a    8 
2    2    b    9 
3    3    c   10 
4    4    d   11 
[1] "Modified DataFrame" 
col1 col2 col3 
1    1    a    8 
2   NA <NA>   NA 
3    2    b    9 
4    3    c   10 
5    4    d   11



My Personal Notes arrow_drop_up
Recommended Articles
Page :