banner



How To Add A Column In R Dplyr

In this cursory tutorial, yous volition larn how to add a column to a dataframe in R. More specifically, you volition learn 1) to add a column using base R (i.eastward., past using the $-operator and brackets, ii) add a column using the add_column() office (i.due east., from tibble), iii) add together multiple columns, and 4) to add together columns from one dataframe to some other.

how to add a column to a dataframe in r

How to add cavalcade to dataframe

Note, when adding a cavalcade with tibble we are, every bit well, going to utilize the %>% operator which is part of dplyr. Note, dplyr, also as tibble, has plenty of useful functions that, apart from enabling us to add columns, make information technology like shooting fish in a barrel to remove a cavalcade by name from the R dataframe (east.m., using the select() office).

Outline

Commencement, before reading an example data gear up from an Excel file, yous are going to go the answer to a couple of questions. Second, we will have a look at the prerequisites to follow this tutorial. Third, we will have a look at how to add a new column to a dataframe using showtime base of operations R and, then, using tibble and the add_column() function. In this section, using dplyr and add_column(), nosotros will also have a quick wait at how we can add an empty column. Note, we will also append a column based on other columns. Furthermore, we are going to acquire, in the 2 last sections, how to insert multiple columns to a dataframe using tibble.

Prerequisites

To follow this tutorial, in which we volition carry out a simple data manipulation chore in R, yous simply need to install dplyr and tibble if y'all desire to use the add_column() and mutate() functions besides as the %>% operator. However, if you lot want to read the instance information, y'all will also need to install the readr packet.

Information technology may be worth noting that all the mentioned packages are all part of the Tidyverse. This bundle comes packed with a lot of tools that tin be used for cleaning information, visualizing data (e.g. to create a besprinkle plot in R with ggplot2).

How practice I add a column to a DataFrame in R?

To add a new column to a dataframe in R yous can utilise the $-operator. For case, to add the cavalcade "NewColumn", you lot can do like this: dataf$NewColumn <- Values. At present, this will effectively add your new variable to your dataset.

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

To add a cavalcade from one dataframe to some other you can use the $ operator. For example, if you desire to add the column named "A" from the dataframe called "dfa" to the dataframe chosen "dfb" you can run the post-obit code. dfb$A <- dfa$A. Adding multiple columns from ane dataframe to another can also be accomplished, of form.

In the next section, we are going to utilise the read_excel() office from the readr parcel. After this, we are going to use R to add together a column to the created dataframe.

Example Data

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

          

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

Lawmaking language: R ( r )

In the code chunk above, nosotros imported the file add_column.xlsx. This file was downloaded to the same directory as the script. Nosotros can obtain some information about the construction of the data using the str() part:

Before going to the next section it may be worth pointing out that it is possible to import data from other formats. For instance, you lot can meet 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 Surround

Now that we have some instance data, to practice with, motility on to the adjacent department in which we volition acquire how to add a new column to a dataframe in base R.

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

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

1) Add a Column Using the $-Operator

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

          

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

Code language: R ( r )

Notation how we used the operator $ to create the new column in the dataframe. What we added, to the dataframe, was a grapheme (i.e., the same word). This will produce a grapheme vector every bit long as the number of rows. Here'south the showtime 6 rows of the dataframe with the added column:

Column added to the r dataframe

If we, on the other hand, tried to assign a vector that is not of the same length as the dataframe, information technology would fail. We would get an mistake similar to "Error: Assigned data `c(2, ane)` must be uniform with existing data." For more than about the dollar sign operator, check the post "How to use $ in R: 6 Examples – list & dataframe (dollar sign operator)".

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

          

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

Code language: R ( r )

new column added to the dataframe in R

Notice how we as well used the dim() office and selected the start element (the number of rows) to create a sequence with the same length as the number of rows. Of course, in a real-life example, nosotros would probably want to specify the sequence a bit more than earlier adding it as a new column. In the adjacent section, we will acquire how to add a new column using brackets.

two) Add a Cavalcade Using Brackets ("[]")

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

          

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

Code language: R ( r )

Using the brackets will give us the same result as using the $-operator. However, it may be easier to utilize the brackets instead of $, sometimes. For example, when we have column names containing whitespaces, brackets may be the mode to go. Also, when selecting multiple columns yous have to use brackets and non $. In the next section, we are going to create a new column past using tibble and the add_column() office.

add column to data frame

adding columns to dataframe

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

Here'south how to add together a column to a dataframe in R:

          

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

Code language: R ( r )

In the example above, we added a new column at "the cease" of the dataframe. Annotation, that we tin can use dplyr to remove columns by proper name. This was done to produce the following output:

Column added to the dataframe with Tibble

Finally, if we want to, we can add a column and create a copy of our quondam dataframe. Change the code so that the left "dataf" is something else e.g. "dataf2". At present, that we have added a column to the dataframe information technology might be time for other data manipulation tasks. For example, nosotros may at present want to remove duplicate rows from the R dataframe or transpose your dataframe.

Example 1: Add a New Cavalcade Later Another Cavalcade

If nosotros desire to suspend a column at a specific position we tin use the .subsequently argument:

          

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

Lawmaking language: R ( r )

Dataframe with column added after another column in R

Equally you probably understand, doing this will add the new cavalcade afterwards the column "A". In the next example, we are going to suspend a column earlier a specified column.

Instance 2: Add a Cavalcade Before Another Cavalcade

Here's how to add a column to the dataframe before some other column:

          

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

Lawmaking language: R ( r )

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

Instance 3: Add an Empty Cavalcade to the Dataframe

Here's how nosotros would practice if we wanted to add an empty column in R:

Notation that we simply added NA (missing value indicator) as the empty column. Here's the output, with the empty cavalcade, added, to the dataframe:

          

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

Lawmaking language: R ( r )

empty column added to the dataframe in R

If we want to practice this we just supercede the NA  with "''", for case. However, this would create a grapheme column and may not exist considered empty.  In the next example, nosotros are going to add a column to a dataframe based on other columns.

r add column to dataframe conditionally

Example iv: Add a Cavalcade Based on Other Columns (Conditionally)

Hither's how to employ R to add a column to a dataframe based on other columns:

          

# Append column conditionally dataf <- dataf %>% add_column(C = if_else(.$A == .$B, TRUE, FALSE))

Code language: R ( r )

In the code chunk above, nosotros added something to the add_column() part: the if_else() part. We did this because nosotros wanted to add a value in the cavalcade based on the value in another cavalcade. Furthermore, we used the .$ so that we get the two columns compared (using ==). If the values in these two columns are the same we add Truthful on the specific row. Here'due south the new column added:

column added based on condition (ie on other column)

Notation, you tin also work with the mutate() office (also from dplyr) to add columns based on conditions. Run into this tutorial for more than data near adding columns on the ground of other columns.

In the next department, we will have a wait 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., column) to a dataframe in R:

          

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

Code language: R ( r )

Notice how nosotros, in the example code to a higher place, calculated a new variable called "low index" which was the hateful of the five columns named Depr1 to Depr5. Obviously, we used the mean() part to calculate the hateful of the columns. Notice how we also used the c_across() office. This was done so that we can calculate the hateful beyond these columns.

added new variable to data in R

Note now that yous have added new columns, to the dataframe, you may also want to rename factor levels in R with e.g. dplyr. In the adjacent section, however, we will add 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() part:

          

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

Lawmaking language: R ( r )

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

multiple columns added to the dataframe

Note, if you desire to add multiple columns, yous simply add an argument as nosotros did above for each column y'all desire to insert. It is, again, important that the length of the vector is the aforementioned as the number of rows in the dataframe. Or else, nosotros volition end up with an error. Note, a more realistic case can be that we want to have the absolute value in R (from e.g. one cavalcade) and add it to a new column. In the next instance, nonetheless, nosotros will add columns from ane dataframe to another.

Add together Columns from One Dataframe to Another Dataframe

In this department, you volition learn how to add together columns from i dataframe to another. Here'due south how you append e.thousand. ii columns from 1 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")])

Code language: R ( r )

added columns from another dataframe

In the case higher up, we used the cbind() role together with selecting which columns we wanted to add. Note, that dplyr has the bind_cols() function that can exist used in a similar fashion. At present that you have put together your data sets you can create dummy variables in R with e.yard. the fastDummies package or calculate descriptive statistics.

Conclusion

In this post, yous take learned how to add a column to a dataframe in R. Specifically, you have learned how to use the base functions bachelor, besides every bit the add_column() function from Tibble. Furthermore, you have learned how to use the mutate() part from dplyr to append a column. Finally, you have likewise learned how to add multiple columns and how to add together columns from i dataframe to some other.

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

Other R Tutorials

Here y'all will find some additional resources that you may find useful- The first iii, here, is especially interesting if you work with datetime objects (e.k., fourth dimension-series data):

  • How to Extract Year from Date in R with Examples with east.g. lubridate (Tidyverse)
  • Learn How to Extract Mean solar day from Datetime in R with Examples with eastward.k. lubridate (Tidyverse)
  • How to Extract Time from Datetime in R – with Examples

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

  • How to utilise %in% in R: 7 Example Uses of the Operator
  • How to utilize 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 In R Dplyr,

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

Posted by: palmerrecance.blogspot.com

0 Response to "How To Add A Column In R Dplyr"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel