R Program to add new row(s) to an existing data frame

How to add a new row(s) to an existing data frame

Here we are explaining how to write an R program to add a new row(s) to an existing data frame. Here we are using a built-in function data.frame(),rbind for this. A data frame is used for storing data tables which has a list of vectors with equal length. The data frames are created by function data.frame(), which has tightly coupled collections of variables. And the function rbind() is an union two or more SparkDataFrames by row. The syntax of this function is,

rbind(…, deparse.level = 1)

– Where dots(…) indicates additional SparkDataFrame(s) and deparse.level is used for matching the signature of the base implementation

How to add a new column in a given data frame in the R program

Below are the steps used in the R program to add a new row(s) to an existing data frame. In this R program, we directly give the data frame to a built-in function. Here we are using variables E, N, S, A, Q for holding different types of vectors. Call the function data.frame() for creating dataframe. Finally, add new row(s) to an existing data frame to a given data frame by calling like E = rbind(E,New_E)

ALGORITHM

  • STEP 1: Assign variables E,N,S,A,Q with vector values
  • STEP 2: First print original vector values
  • STEP 3: Add a new column in a given data frame as E = rbind(E,New_E)
  • STEP 4: Print the final data frame

R Source Code

E = data.frame(
                N = c('Jhon', 'Hialy', 'Albert', 'James', 'Delma'),
                S = c(10, 9.5, 12.2, 11, 8),
                A = c(2, 1, 2, 4, 1),
                Q = c('yes', 'no', 'yes', 'no', 'no')
              )

print("Original dataframe:")
## [1] "Original dataframe:"
print(E)
##        N    S A   Q
## 1   Jhon 10.0 2 yes
## 2  Hialy  9.5 1  no
## 3 Albert 12.2 2 yes
## 4  James 11.0 4  no
## 5  Delma  8.0 1  no
New_E = data.frame(
                    N = c('Rooby', 'Lucas'),
                    S = c(3, 7),
                    A = c(2, 5),
                    Q = c('yes', 'no')
                  )

E =  rbind(E,New_E)
print("After adding new row(s) to an existing data frame:")
## [1] "After adding new row(s) to an existing data frame:"
print(E)
##        N    S A   Q
## 1   Jhon 10.0 2 yes
## 2  Hialy  9.5 1  no
## 3 Albert 12.2 2 yes
## 4  James 11.0 4  no
## 5  Delma  8.0 1  no
## 6  Rooby  3.0 2 yes
## 7  Lucas  7.0 5  no