Browse Author: Hila

How to join two or more attributes (variables), or to create a concatenation in R

Very commonly we encounter a situation where we have to join two or more attributes (variables) in our dataset. This is mainly when the function or command we would like to run can be run only with one attribute. We will show in this post two ways how to merge between two attributes in R.

In the following example we have a dataset ‘Project’ with two numeric vectors – Year and Month.

Post 1

Now we would like to create a new vector – ‘YearMonth’ which is a combination of the two numeric vectors.

One way to do so is to specify the values and create a code specification for each combination, as can be seen here..

Project$YearMonth[Project$Year==2013 & Project$Month==1] <- “2013.1” Project$YearMonth[Project$Year==2013 & Project$Month==2] <- “2013.2” Project$YearMonth[Project$Year==2013 & Project$Month==3] <- “2013.3” Project$YearMonth[Project$Year==2013 & Project$Month==4] <- “2013.4”

This is of course a very time-consuming and therefore not recommended.

A quicker way and much preferred is to create an automatic joint command. This can be done with the following command


Project$YearMonth <- paste(Project$Year, Project$Month, sep = “.”)


This command merge the values of the ‘Year’ and ‘Month’ attributes at the ‘Project’ dataset, and separating the values with a dot (.).*

* When no value is included, no space is introduced (sep = “.”) the values of the two attribute seen as one.

And here is our ‘Project’ dataset with the joint ‘YearMonth’ vector.

Post 2

Happy Analysing!

Questions? Comments? Drop us a line..