banner



how to add a row to a dataframe in r

Introduction

In one of my previous articles, we learned practically about the Data Frame in R. Now, we will learn to perform the operations on R Data Frame - adding and removing Rows to a Data Frame in R. Apart from this, we will also learn to merge a Data Frame in R. At last, we will learn to summarize the Data Frame in R.

Let's start now.

Data Frame in R

Data Frame in R is a data type. It is a two-dimensional object. It can contain different data type elements like numeric, character or logical in different columns. Here, one thing we need to remember is that while creating it, in any single column, all the elements should be of the same type i.e., either numeric, character, logic or something else.

We had created a Data Frame of the world population in R, as shown below, using the following code.

R Data Frame Operations

  1. Rank <-1 : 10
  2. Country <- c("China" , "India" , "United States" , "Indonesia" , "Pakistan" , "Brazil" ,
  3. "Nigeria" , "Bangladesh" , "Russia" , "Mexico" )
  4. Population.2019  <- c( 1433783686 , 1366417754 , 329064917 , 270625568 , 216565318 ,
  5. 211049527 , 200963599 , 163046161 , 145872256 , 127575529 )
  6. Population.2018  <- c( 1427647786 , 1352642280 , 327096265 , 267670543 , 212228286 ,
  7. 209469323 , 195874683 , 161376708 , 145734038 , 126190788 )
  8. Growth.Rate <- c("0.43%" , "1.02%" , "0.60%" , "1.10%" , "2.04%" , "0.75%" , "2.60%" ,
  9. "1.03%" , "0.09%" , "1.10%" )
  10. DataFrame.WorldPopulation <- data.frame(Rank, Country, Population.2019 , Population. 2018 ,
  11.                                         Growth.Rate)
  12. DataFrame.WorldPopulation

Now, we will perform operations on the above Data Frame in R Studio which are as shown below.

Printing Structure of Data Frame/R Object

We can print and observe the structure of the Data Frame in R by simply using the str(<object>) function as shown below. To know more about str(<obj>) function, you can follow the R documentation str() function in R.

  1. str(DataFrame.WorldPopulation)

It will give the following result with the overall structure, like the number of rows, columns, some of the elements of each column.

R Data Frame Operations

Adding Observation/Row To R Data Frame

To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.

The basic syntax of rbind() is as shown below.

  1. rbind(<old existing object>, <new object to be added>)

Now we shall learn to add the observations/rows using rbind() below.

Adding Single Observation / Row To R Data Frame

To add a single observation at a time to an existing data frame we will use the following steps.

  • Create a new Data Frame of the same number of variables/columns.
  • Name the newly created Data Frame variable as of old Data Frame in which you want to add this observation.
  • Use the rbind() function to add a new observation.

The above said steps have been implemented in the below example.

  1. Japan.Population <- data.frame(11 , "Japan" , 126860301 , 127202192 , "-0.27%" )
  2. names(Japan.Population) <- c("Rank" , "Country" , "Population.2019" , "Population.2018" , "Growth.Rate" )
  3. WorldPopulation.Newdf <- rbind(DataFrame.WorldPopulation, Japan.Population)

Now we have already inserted the observation/row to the existing Data Frame of name DataFrame.WorldPopulation and created a new data frame of name WorldPopulation.Newdf as shown in the above example.

Now, we can easily see the above added observation by printing the new Data Frame, as shown below.

  1. WorldPopulation.Newdf

We can check the structure of the newly created Data Frame using the str() function.

  1. str(WorldPopulation.Newdf)

As we can see clearly the structure of new data frame of the name WorldPopulation.New has been changed. Previously, it had only 10 observations but now, it has 11 observations after inserting one observation. Here, the variable has the same 5 variables in both data frames as we have not done any insertion/removal to the variable/column of the data frame.

Adding Multiple Observations/Rows To R Data Frame

Adding single observations one by one is a repetitive, time-consuming, as well as, a boring task. Hence we will learn to add multiple observations at a time in one attempt. Here also we will use the same rbind() function.

We can use the below steps to add multiple observations at a time.

  • Create a new Data Frame of the same number of variables/columns with the help of vector.
  • Name the newly created Data Frame variable as of old Data Frame in which you want to add these observations.
  • Use the rbind() function to add new observations.

The above steps are shown below.

  1. Df.NewCountryPopulation <- data.frame(c(11 , 12 , 13 , 14 , 15 ),
  2.                                c("Japan" , "Ethiopia" , "Philippines" , "Egypt" , "Vietnam" ),
  3.                                c(10 , 10 , 10 , 10 , 10 ),
  4.                                c(10 , 10 , 10 , 10 , 10 ),
  5.                                c("5%" , "10%" , "12%" , "14%" , "19%" ))
  6. names(Df.NewCountryPopulation) <- c("Rank" , "Country" , "Population.2019" , "Population.2018" , "Growth.Rate" )
  7. Df.NewWorldPopulationAfterObs <- rbind(DataFrame.WorldPopulation, Df.NewCountryPopulation)

As we have already added multiple observations to the existing data frame using the above code, now we can easily print the newly created data frame elements and their structure as shown below.

  1. Df.NewWorldPopulationAfterObs

It will print the data frame elements with all the above-added observations as shown in the below image. Here one thing we need to care is that the new data frame is showing 15 observations, not 16 observations and it is because we have added the observations to the data frame created in the first step i.e., original data frame which had only 10 observations. So, after adding the new 5 observations it has become 15 observations.

Now we can also print and see the structure of the above data frame to verify the number of the observations as shown below.

  1. str(Df.NewWorldPopulationAfterObs)

Adding Observations/Rows Using R Package

We can use R package or library which name is tidyverse which has built-in function add_row() to add the observation to an existing data frame. To know more about the package in R you can follow the link of my previous article Package in R. Now we will add observation here by using add_row() function as shown below,

  1. install.packages("tidyverse" )
  2. library(tidyverse)
  3. DataFrame.WorldPopulation %>% add_row(Rank =49 , Country = "Nepal" ,
  4.                                       Population.2019  = 28608710 ,
  5.                                       Population.2018  = 28095714 ,
  6.                                       Growth.Rate ="1.83%" )

When we execute the above code, it adds the observation and prints also.

Adding Variable/Column To R Data Frame

So far we have learned how to add observations/rows to the existing data frame. Now we will learn how to add the variables/column to the existing data frame in R.

Adding Single Variable/Column To R Data Frame

The basic syntax for adding a variable or a column to an existing R data frame is very simple which is as shown below.

  1. <Existing Data Frame>$ <Variable/Column Name> <- <Object/Value of Variable>

The below example shows the above concept; i.e., adding a single variable/column to data frame. It will a add a new column of name Area.kmSquare.

Here one thing we might see is that the name of the column is not in the square format. It is because every language has some rules and regulation of naming the variable. To know more about the variable and data type in R and their naming convention rule you can follow the article Variables And Data Types In R.

  1. DataFrame.WorldPopulation$Area.kmSquare <- c(9706961 , 3287590 , 9372610 , 1904569 , 881912 , 8515767 , 923768 , 147570 , 17098242 , 1964375 )

Now we can easily print the data frames and their structure also to see the newly added variable or column.

Now when we print the structure of the above data frame it shows the output as shown below. Now the number of variables/columns has become 6 after adding one new column. Before adding a new column the number of variables was 5.

Adding Multiple Variables/Columns To R Data Frame

We can add multiple variables/columns to a data frame using cbind() function. To add the multiple columns to a data frame we need to follow the below steps.

  • Create a new Data Frame with an individual column using vector c() function.
  • Use the cbind() function to add a new data frame as the variables.

The above steps have been implemented below in R studio.

  1. NewCountry.Df <- data.frame(
  2.         DensityPerKmSquare = c(148 , 416 , 35 , 142 , 246 , 25 , 218 , 1105 , 9 , 65 ),
  3.         GDP2019.PPP.InBillions = c(14172.20 , 2957.72 , 21482.41 , 1066.84 , 298.31 ,
  4. 1929.71 , 447.01 , 313.51 , 4345.36 , 2696.45 ))
  5. DataFrame.WorldPopulation <- cbind(DataFrame.WorldPopulation, NewCountry.Df)

Now, the columns have been added successfully, we can easily print and see the newly added columns by printing the data frame as shown in the below image.

  1. DataFrame.WorldPopulation

When we print the structure of the data frame it shows 8 variables/columns as it has 6 columns and we have added 2 columns using cbind() function just now. It has been shown below.

Remember While Adding Observation/Variables To R Data Frame

One thing we need to keep in mind while adding rows or columns to an existing data frame is that when a column is added, then the number of elements should be equal to the number of rows to the existing data frame in which we are going to add the column. On the other hand, while adding rows the number of elements in the rows should be equal to the number of columns to the existing data frame. Otherwise, it will give the exception and some of the column value will be added as NA.

This has been shown and described by the below image.

If the above instruction is not followed at the time of adding observation or variables, then it will display the following exception. Here you can see clearly that it is giving a differing number of elements exception because in one column it has 10 element while in another it has only 9 elements.

Subsetting/Filtering R Data Frame Elements

We can subset and filter elements of a R Data Frame in different ways. To know how to filter or subset the R data frame element you can follow one of my previous article Data Frame in R..

Summary

In this article, we have learned and explored about the Data Frame operations in R. We learned how to add observations/rows and variables/columns to an existing data frame in R using different ways. Apart from these we learned and recalled to use the package in R.

I hope you learned and enjoyed it. I look forward to seeing your feedback.

how to add a row to a dataframe in r

Source: https://www.c-sharpcorner.com/article/r-data-frame-operations-adding-rows-removing-rows-and-merging-two-data-frame/

Posted by: laraopeashom.blogspot.com

0 Response to "how to add a row to a dataframe in r"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel