How To Add Two Columns In R
In this brief tutorial, you lot volition learn how to add together a column to a dataframe in R. More specifically, you volition learn ane) to add a column using base of operations R (i.due east., by using the $-operator and brackets, 2) add together a column using the add_column() function (i.eastward., from tibble), 3) add multiple columns, and iv) to add together columns from one dataframe to another.
Note, when adding a column with tibble we are, too, going to use the %>%
operator which is part of dplyr. Note, dplyr, as well as tibble, has plenty of useful functions that, autonomously from enabling united states of america to add columns, make information technology piece of cake to remove a column past name from the R dataframe (e.g., using the select()
role).
Outline
Beginning, before reading an instance information gear up from an Excel file, you are going to become the respond to a couple of questions. Second, nosotros will take a look at the prerequisites to follow this tutorial. Third, we will have a look at how to add a new cavalcade to a dataframe using first base R and, then, using tibble and the add_column()
function. In this department, using dplyr and add_column()
, nosotros will also take a quick wait at how we tin add an empty column. Notation, we volition besides append a column based on other columns. Furthermore, we are going to learn, in the ii 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 task in R, you but need to install dplyr and tibble if y'all want to utilise the add_column()
and mutate()
functions too as the %>% operator. However, if you desire to read the instance information, yous will as well need to install the readr parcel.
It may be worth noting that all the mentioned packages are all function of the Tidyverse. This package comes packed with a lot of tools that tin be used for cleaning data, visualizing data (east.thou. to create a scatter plot in R with ggplot2).
How exercise I add a column to a DataFrame in R?
To add a new column to a dataframe in R you can use the $-operator. For example, to add the column "NewColumn", you can do like this: dataf$NewColumn <- Values
. Now, this will effectively add your new variable to your dataset.
How do I add a column from i Dataframe to another in R?
To add a column from one dataframe to another you can utilize the $ operator. For example, if you want to add the cavalcade named "A" from the dataframe chosen "dfa" to the dataframe called "dfb" you can run the following code. dfb$A <- dfa$A
. Adding multiple columns from ane dataframe to another can also be achieved, of course.
In the next section, we are going to use the read_excel()
role from the readr package. Afterward this, nosotros are going to use R to add a column to the created dataframe.
Instance Data
Hither's 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 above, nosotros imported the file add_column.xlsx. This file was downloaded to the aforementioned directory as the script. We can obtain some information about the structure of the information using the str()
function:
Earlier going to the adjacent department it may be worth pointing out that it is possible to import data from other formats. For case, yous 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 Environs
At present that we have some example data, to exercise with, movement on to the adjacent section in which we will learn how to add together a new cavalcade to a dataframe in base R.
Two Methods to Add together a Column to a Dataframe in R (Base).
Start, nosotros will apply the $-operator and assign a new variable to our dataset. Second, nosotros volition use brackets ("[ ]") to exercise the same.
ane) Add a Column Using the $-Operator
Here'due south how to add a new column to a dataframe using the $-operator in R:
# add column to dataframe dataf$Added_Column <- "Value"
Code linguistic communication: R ( r )
Note how we used the operator $ to create the new column in the dataframe. What we added, to the dataframe, was a graphic symbol (i.eastward., the same discussion). This volition produce a character vector as long as the number of rows. Here'due south the get-go 6 rows of the dataframe with the added column:
If nosotros, on the other paw, tried to assign a vector that is not of the same length equally the dataframe, it would neglect. We would get an error similar to "Fault: Assigned information `c(2, one)` must be compatible with existing data." For more about the dollar sign operator, bank check the mail "How to apply $ in R: vi Examples – list & dataframe (dollar sign operator)".
If nosotros would like to add a sequence of numbers we can use seq()
function and the length.out
argument:
# add column to dataframe dataf$Seq_Col <- seq(1, 10, length.out = dim(dataf)[1])
Code language: R ( r )
Discover how we also used the dim()
function and selected the kickoff element (the number of rows) to create a sequence with the same length equally the number of rows. Of course, in a real-life example, we would probably desire to specify the sequence a bit more before adding it as a new column. In the next section, we will learn how to add a new column using brackets.
2) Add a Column Using Brackets ("[]")
Here's how to append a column to a dataframe in R using brackets ("[]"):
# Calculation a new column dataf["Added_Column"] <- "Value"
Lawmaking language: R ( r )
Using the brackets will give united states the same result as using the $-operator. However, it may be easier to use the brackets instead of $, sometimes. For example, when we have column names containing whitespaces, brackets may be the mode to go. As well, when selecting multiple columns yous have to use brackets and not $. In the next section, we are going to create a new column by using tibble and the add_column()
function.
How to Add a Column to a dataframe in R using the add_column() Office
Here's how to add a column to a dataframe in R:
# Append column using Tibble: dataf <- dataf %>% add_column(Add_Column = "Value")
Code language: R ( r )
In the instance in a higher place, we added a new cavalcade at "the cease" of the dataframe. Note, that we can use dplyr to remove columns by name. This was done to produce the following output:
Finally, if we want to, nosotros can add a cavalcade and create a re-create of our former dataframe. Modify the code then that the left "dataf" is something else east.g. "dataf2". Now, that we have added a column to the dataframe information technology might exist time for other information manipulation tasks. For instance, nosotros may at present desire to remove duplicate rows from the R dataframe or transpose your dataframe.
Example 1: Add a New Column After Some other Column
If we want to append a column at a specific position we tin use the .after
statement:
# R add column after another column dataf <- dataf %>% add_column(Column_After = "Afterwards", .after = "A")
Lawmaking language: R ( r )
As you lot probably understand, doing this will add the new column subsequently the column "A". In the next instance, we are going to suspend a column before a specified column.
Example ii: Add a Column Before Another Cavalcade
Hither's how to add a column to the dataframe earlier another cavalcade:
# R add column before another column dataf <- dataf %>% add_column(Column_Before = "Before", .subsequently = "Price")
Lawmaking language: R ( r )
In the next example, we are going to employ add_column()
to add together an empty column to the dataframe.
Example 3: Add an Empty Column to the Dataframe
Hither'south how we would do if nosotros wanted to add an empty column in R:
Note that we but added NA (missing value indicator) equally the empty cavalcade. Here's the output, with the empty cavalcade, added, to the dataframe:
# Empty dataf <- dataf %>% add_column(Empty_Column = NA) %>%
Lawmaking language: R ( r )
If we want to practise this we just replace the NA
with "''", for example. However, this would create a grapheme cavalcade and may not be considered empty. In the next instance, nosotros are going to add a column to a dataframe based on other columns.
Example 4: Add together a Column Based on Other Columns (Conditionally)
Here'southward how to use 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 to a higher place, we added something to the add_column()
role: the if_else()
function. Nosotros did this because nosotros wanted to add a value in the column based on the value in another column. Furthermore, we used the .$
then that nosotros get the two columns compared (using ==
). If the values in these two columns are the same nosotros add together Truthful
on the specific row. Here'southward the new column added:
Notation, you can also work with the mutate()
role (too from dplyr) to add columns based on atmospheric condition. Meet this tutorial for more data about calculation columns on the basis of other columns.
In the side by side section, nosotros volition have a look at how to work with the mutate()
function to compute, and add together 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 a new variable (i.eastward., column) to a dataframe in R:
# insert new column with mutate dataf <- dataf %>% mutate(DepressionIndex = mean(c_across(Depr1:Depr5))) %>% caput()
Code linguistic communication: R ( r )
Notice how we, in the example code above, calculated a new variable called "depression index" which was the mean of the 5 columns named Depr1 to Depr5. Obviously, we used the mean()
office to calculate the mean of the columns. Notice how we also used the c_across()
function. This was washed so that we can calculate the hateful beyond these columns.
Note now that y'all have added new columns, to the dataframe, you may likewise want to rename factor levels in R with e.chiliad. dplyr. In the next section, all the same, we will add multiple columns to a dataframe.
How to Add together Multiple Columns to the Dataframe in R
Here'southward how you would insert multiple columns, to the dataframe, using the add_column()
office:
# Add multiple columns dataf <- %>% add_column(New_Column1 = "1st Column Added", New_Column2 = "2nd Column Added")
Lawmaking linguistic communication: R ( r )
In the example code in a higher place, we had two vectors ("a" and "b"). Now, we so used the add_column()
method to suspend these two columns to the dataframe. Here's the first 6 rows of the dataframe with added columns:
Note, if you want to add multiple columns, you just add an argument as we did to a higher place for each column you want to insert. It is, once more, important that the length of the vector is the same as the number of rows in the dataframe. Or else, we volition end upwards with an error. Note, a more realistic example can be that we want to have the absolute value in R (from e.g. one column) and add it to a new column. In the adjacent case, however, nosotros will add columns from one dataframe to some other.
Add together Columns from Ane Dataframe to Another Dataframe
In this section, you volition learn how to add together columns from one dataframe to another. Here's how you append east.g. two columns from i dataframe to another:
# Read information 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 )
In the example above, we used the cbind()
function together with selecting which columns we wanted to add together. Note, that dplyr has the bind_cols()
part that can be used in a similar fashion. Now that you have put together your data sets you can create dummy variables in R with due east.g. the fastDummies package or calculate descriptive statistics.
Determination
In this post, you have learned how to add together a column to a dataframe in R. Specifically, y'all have learned how to apply the base functions available, as well as the add_column() office from Tibble. Furthermore, you have learned how to apply the mutate() function from dplyr to suspend a column. Finally, you have also learned how to add multiple columns and how to add columns from ane dataframe to another.
I hope you learned something valuable. If you did, please share the tutorial on your social media accounts, add a link to it in your projects, or only go out a comment beneath! Finally, suggestions and corrections are welcomed, also as comments below.
Other R Tutorials
Here yous will find some boosted resources that you may notice useful- The first three, here, is especially interesting if you work with datetime objects (e.g., fourth dimension-serial data):
- How to Extract Twelvemonth from Date in R with Examples with e.g. lubridate (Tidyverse)
- Learn How to Extract Day 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 2 posts might be useful:
- How to employ %in% in R: vii Example Uses of the Operator
- How to apply the Repeat and Replicate functions in R
- How to Create a Matrix in R with Examples – empty, zeros
How To Add Two Columns In R,
Source: https://www.marsja.se/how-to-add-a-column-to-dataframe-in-r-with-tibble-dplyr/
Posted by: kelleyandon1984.blogspot.com
0 Response to "How To Add Two Columns In R"
Post a Comment