banner



How To Add A Column To A Data Frame In R

In this brief tutorial, you volition learn how to add a column to a dataframe in R. More specifically, yous volition acquire 1) to add a column using base R (i.e., by using the $-operator and brackets, 2) add a column using the add_column() part (i.eastward., from tibble), 3) add multiple columns, and four) to add columns from ane dataframe to another.

how to add a column to a dataframe in r

How to add cavalcade to dataframe

Annotation, when adding a column with tibble nosotros are, as well, going to use the %>% operator which is part of dplyr. Note, dplyr, as well as tibble, has plenty of useful functions that, apart from enabling us to add together columns, make information technology easy to remove a column by name from the R dataframe (east.g., using the select() function).

Outline

First, before reading an example data set from an Excel file, you are going to get the respond to a couple of questions. 2d, we will have a look at the prerequisites to follow this tutorial. Tertiary, we volition have a look at how to add a new column to a dataframe using first base of operations R and, then, using tibble and the add_column() function. In this section, using dplyr and add_column(), we will likewise have a quick look at how we can add an empty cavalcade. Note, we will as well suspend a column based on other columns. Furthermore, we are going to larn, in the two last sections, how to insert multiple columns to a dataframe using tibble.

Prerequisites

To follow this tutorial, in which nosotros will carry out a simple data manipulation task in R, you lot merely need to install dplyr and tibble if yous desire to utilise the add_column() and mutate() functions likewise as the %>% operator. However, if you want to read the example data, y'all volition besides need to install the readr package.

It may be worth noting that all the mentioned packages are all role of the Tidyverse. This package comes packed with a lot of tools that can exist used for cleaning data, visualizing data (e.one thousand. to create a scatter plot in R with ggplot2).

How do I add a cavalcade to a DataFrame in R?

To add a new cavalcade to a dataframe in R yous can use the $-operator. For example, to add the cavalcade "NewColumn", y'all can do like this: dataf$NewColumn <- Values. Now, this will effectively add your new variable to your dataset.

How do I add together a column from one Dataframe to another in R?

To add a cavalcade from ane dataframe to another you can apply the $ operator. For instance, if you want to add the column named "A" from the dataframe called "dfa" to the dataframe called "dfb" you can run the following lawmaking. dfb$A <- dfa$A. Adding multiple columns from one dataframe to some other can too exist accomplished, of course.

In the next section, we are going to use the read_excel() function from the readr packet. Subsequently this, nosotros are going to use R to add together a column to the created dataframe.

Example Information

Here'southward how to read a .xlsx file in R:

          

# Import readxl library(readxl) # Read information from .xlsx file dataf <- read_excel('./SimData/add_column.xlsx')

Code language: R ( r )

In the code chunk in a higher place, we imported the file add_column.xlsx. This file was downloaded to the same directory as the script. We can obtain some information most the construction of the data using the str() function:

Before going to the next section it may exist worth pointing out that it is possible to import data from other formats. For case, you can see a couple of tutorials covering how to read data from SPSS, Stata, and SAS:

  • How to Read and Write Stata (.dta) Files in R with Haven
  • Reading SAS Files in R
  • How to Read & Write SPSS Files in R Statistical Environment

Now that we have some example data, to practice with, motility on to the next section in which nosotros will learn how to add a new column to a dataframe in base R.

Two Methods to Add together a Column to a Dataframe in R (Base).

First, we will use the $-operator and assign a new variable to our dataset. Second, we volition use brackets ("[ ]") to practise the same.

ane) Add a Column Using the $-Operator

Here's how to add a new column to a dataframe using the $-operator in R:

          

# add column to dataframe dataf$Added_Column <- "Value"

Code language: R ( r )

Annotation how we used the operator $ to create the new column in the dataframe. What we added, to the dataframe, was a character (i.e., the same word). This volition produce a graphic symbol vector every bit long every bit the number of rows. Here's the first 6 rows of the dataframe with the added cavalcade:

Column added to the r dataframe

If nosotros, on the other paw, tried to assign a vector that is not of the same length as the dataframe, information technology would fail. We would become an error like to "Error: Assigned data `c(2, one)` must be compatible with existing data." For more about the dollar sign operator, check the mail "How to employ $ in R: half dozen Examples – list & dataframe (dollar sign operator)".

If nosotros would similar to add together a sequence of numbers we can utilise seq() function and the length.out argument:

          

# add together column to dataframe dataf$Seq_Col <- seq(1, ten, length.out = dim(dataf)[1])

Lawmaking linguistic communication: R ( r )

new column added to the dataframe in R

Observe how we likewise used the dim() function and selected the outset element (the number of rows) to create a sequence with the aforementioned length equally the number of rows. Of course, in a real-life example, we would probably desire to specify the sequence a bit more than before adding information technology as a new cavalcade. In the next section, we volition learn how to add together a new column using brackets.

2) Add a Column Using Brackets ("[]")

Hither's how to append a cavalcade to a dataframe in R using brackets ("[]"):

          

# Adding a new cavalcade dataf["Added_Column"] <- "Value"

Lawmaking language: R ( r )

Using the brackets volition give u.s.a. the aforementioned result every bit using the $-operator. Yet, information technology may be easier to use the brackets instead of $, sometimes. For case, when we take column names containing whitespaces, brackets may exist the manner to get. Likewise, when selecting multiple columns y'all accept to apply brackets and not $. In the side by side section, we are going to create a new cavalcade by using tibble and the add_column() office.

add column to data frame

adding columns to dataframe

How to Add a Column to a dataframe in R using the add_column() Office

Here's how to add a cavalcade to a dataframe in R:

          

# Append column using Tibble: dataf <- dataf %>% add_column(Add_Column = "Value")

Code language: R ( r )

In the instance higher up, nosotros added a new column at "the stop" of the dataframe. Notation, that nosotros tin can use dplyr to remove columns past name. This was done to produce the post-obit output:

Column added to the dataframe with Tibble

Finally, if we want to, nosotros tin add a column and create a copy of our one-time dataframe. Change the lawmaking so that the left "dataf" is something else eastward.thousand. "dataf2". Now, that we have added a column to the dataframe it might be fourth dimension for other data manipulation tasks. For case, nosotros may now want to remove duplicate rows from the R dataframe or transpose your dataframe.

Instance 1: Add together a New Column After Some other Column

If we want to suspend a column at a specific position we tin can use the .afterwards statement:

          

# R add column after another column dataf <- dataf %>% add_column(Column_After = "Later on", .afterwards = "A")

Code language: R ( r )

Dataframe with column added after another column in R

As yous probably understand, doing this will add the new column later on the column "A". In the next case, we are going to append a column before a specified cavalcade.

Example two: Add together a Column Before Another Cavalcade

Here'due south how to add a cavalcade to the dataframe earlier another column:

          

# R add column before another cavalcade dataf <- dataf %>% add_column(Column_Before = "Before", .subsequently = "Cost")

Code language: R ( r )

In the next example, we are going to use add_column() to add an empty cavalcade to the dataframe.

Instance 3: Add an Empty Column to the Dataframe

Here'due south how we would practise if we wanted to add an empty column in R:

Annotation that we just added NA (missing value indicator) as the empty cavalcade. Here'southward the output, with the empty column, added, to the dataframe:

          

# Empty dataf <- dataf %>% add_column(Empty_Column = NA) %>%

Code language: R ( r )

empty column added to the dataframe in R

If we want to practise this nosotros only replace the NA  with "''", for example. Still, this would create a graphic symbol column and may not be considered empty.  In the next example, we are going to add a cavalcade to a dataframe based on other columns.

r add column to dataframe conditionally

Example 4: Add a Column Based on Other Columns (Conditionally)

Here's how to use R to add together a column to a dataframe based on other columns:

          

# Suspend column conditionally dataf <- dataf %>% add_column(C = if_else(.$A == .$B, True, Fake))

Code language: R ( r )

In the code clamper higher up, we added something to the add_column() role: the if_else() function. Nosotros did this because we wanted to add a value in the column based on the value in some other column. Furthermore, we used the .$ so that we get the two columns compared (using ==). If the values in these 2 columns are the aforementioned we add Truthful on the specific row. Here'due south the new column added:

column added based on condition (ie on other column)

Note, you can also piece of work with the mutate() function (as well from dplyr) to add together columns based on conditions. Meet this tutorial for more information about adding columns on the footing of other columns.

In the next section, we will accept a look at how to work with the mutate() function to compute, and add a new variable to the dataset.

Compute and Add a New Variable to a Dataframe in R with mutate()

Here's how to compute and add together a new variable (i.e., cavalcade) to a dataframe in R:

          

# insert new column with mutate dataf <- dataf %>% mutate(DepressionIndex = mean(c_across(Depr1:Depr5))) %>% head()

Code language: R ( r )

Detect how we, in the example lawmaking above, calculated a new variable called "low index" which was the mean of the 5 columns named Depr1 to Depr5. Obviously, we used the hateful() function to calculate the mean of the columns. Notice how nosotros also used the c_across() part. This was washed so that we tin summate the mean across these columns.

added new variable to data in R

Annotation now that you have added new columns, to the dataframe, you may besides desire to rename factor levels in R with e.thou. dplyr. In the next section, however, we will add together multiple columns to a dataframe.

How to Add Multiple Columns to the Dataframe in R

Hither's how you would insert multiple columns, to the dataframe, using the add_column() function:

          

# Add multiple columns dataf <- %>% add_column(New_Column1 = "1st Column Added", New_Column2 = "2nd Column Added")

Lawmaking linguistic communication: R ( r )

In the instance code to a higher place, we had two vectors ("a" and "b"). Now, nosotros and so used the add_column() method to append these two columns to the dataframe. Here's the first six rows of the dataframe with added columns:

multiple columns added to the dataframe

Note, if you want to add multiple columns, you lot just add an argument equally we did above for each cavalcade you want to insert. It is, again, of import that the length of the vector is the same equally the number of rows in the dataframe. Or else, we will end upwardly with an error. Notation, a more realistic case can be that nosotros want to take the absolute value in R (from east.chiliad. one column) and add it to a new cavalcade. In the next instance, however, we will add together columns from one dataframe to another.

Add Columns from One Dataframe to Another Dataframe

In this section, y'all will learn how to add columns from one dataframe to some other. Here'south how you append e.g. ii columns from one dataframe to another:

          

# Read data from the .xlsx files: dataf <- read_excel('./SimData/add_column.xlsx') dataf2 <- read_excel('./SimData/add_column2.xlsx') # Add the columns from the second dataframe to the first dataf3 <- cbind(dataf, dataf2[c("Anx1", "Anx2", "Anx3")])

Lawmaking language: R ( r )

added columns from another dataframe

In the example above, nosotros used the cbind() function together with selecting which columns we wanted to add together. Notation, that dplyr has the bind_cols() part that can be used in a like fashion. At present that you accept put together your information sets you can create dummy variables in R with e.chiliad. the fastDummies bundle or calculate descriptive statistics.

Decision

In this post, you lot have learned how to add a cavalcade to a dataframe in R. Specifically, you accept learned how to apply the base functions available, as well as the add_column() part from Tibble. Furthermore, y'all have learned how to use the mutate() function from dplyr to append a column. Finally, you have also learned how to add together multiple columns and how to add together columns from i dataframe to another.

I promise you lot learned something valuable. If yous did, delight share the tutorial on your social media accounts, add a link to it in your projects, or merely go out a comment below! Finally, suggestions and corrections are welcomed, also as comments below.

Other R Tutorials

Here you will notice some additional resource that you lot may find useful- The get-go three, hither, is particularly interesting if you work with datetime objects (eastward.g., time-series data):

  • How to Extract Year from Date in R with Examples with eastward.g. lubridate (Tidyverse)
  • Larn How to Excerpt Twenty-four hour period from Datetime in R with Examples with eastward.g. lubridate (Tidyverse)
  • How to Extract Time from Datetime in R – with Examples

If you are interested in other useful functions and/or operators these two posts might be useful:

  • How to apply %in% in R: 7 Example Uses of the Operator
  • How to use the Repeat and Replicate functions in R
  • How to Create a Matrix in R with Examples – empty, zeros

add column to dataframe in R

How To Add A Column To A Data Frame In R,

Source: https://www.marsja.se/how-to-add-a-column-to-dataframe-in-r-with-tibble-dplyr/

Posted by: negronandeverien.blogspot.com

0 Response to "How To Add A Column To A Data Frame In R"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel