One of the big issues when it comes to working with data in any context is the issue of data cleaning and merging of datasets, since it is often the case that you will find yourself having to collate data across multiple files, and will need to rely on R to carry out functions that you would normally carry out using commands like
VLOOKUP in Excel.
Data Cleaning and Merging Functions
For our example, we have two datasets:
- sales: This file contains the variables Date, ID (which is Product ID), and Sales. We load this into R under the name
customers: This file contains the variables ID, Age, and Country. We load this into R under the name
The following are examples of popular techniques employed in R to clean a dataset, along with how to format variables effectively to facilitate analysis. The below functions work particularly well with panel datasets, where we have a mixture of cross-sectional and time series data.
1. Storing variables in a data frame
To start off with a simple example, let us choose the customers dataset. Suppose that we only wish to include the variables ID and Age in our data. To do this, we define our data frame as follows:
2. Mimic VLOOKUP by using the merge functions
Often times, it is necessary to combine two variables from different datasets similar to how VLOOKUP is used in Excel to join two variables based on certain criteria. In R, this can be done using the
For instance, suppose that we wish to link the Date variable in the sales dataset with the Age and Country variables in the customers dataset – with the ID variable being the common link.
Therefore, we do as follows:
mergeinfo<-merge(mydata[, c("ID", "Sales")],mydata2[, c("ID", "Age", "Country")])
Upon doing this, we see that a new dataset is formed in R joining our chosen variables:
3. Using as.date to format dates and calculate duration
Suppose that we now wish to calculate the number of days between the current date and the date of sale as listed in the sales file. In order to accomplish this, we can use as.date as follows:
Going back to the example above, suppose that we now wish to combine this duration variable with the rest of our data.
Hence, we can now combine our new Duration variable with the
merge function as above, and can do this as follows:
4. Using as.POSIXct and format to calculate differences between seconds
While it is not the case in the above example, a situation can often occur where we have dates which include the time, e.g. “2016-10-13 19:30:55”.
There may be times where we wish to find differences between seconds of two dates. In this regard, as.POSIXct is a more suitable option than as.Date. For instance, we can first format our date as follows:
date_converted<-format(Date, format="%Y-%m-%d %H:%M:%S")
When we define our seconds variable, it will now give us the difference between two dates in seconds. Then, it is a matter of simple arithmetic to obtain the difference in minutes and seconds.
4. grepl: Remove instances of a string from a variables
Let us look to the Country variable. Suppose that we wish to remove all instances of “Greenland” from our variable. This is accomplished using the grepl command:
5. Delete observations using head and tail functions
The head and tail functions can be used if we wish to delete certain observations from a variable, e.g. Sales. The head function allows us to delete the first 30 rows, while the tail function allows us to delete the last 30 rows.
When it comes to using a variable edited in this way for calculation purposes, e.g. a regression, the as.matrix function is also used to convert the variable into matrix format:
6. Replicate SUMIF using the “aggregate” function
names <- c("John", "Elizabeth", "Michael", "John", "Elizabeth", "Michael")
webvisitsframe <- cbind("24","32","40","71","65","63")
minutesspentframe <- cbind("20", "41", "5", "6", "48", "97")
Let us suppose that we have created the following table as below, and want to obtain the sum of web visits and minutes spent on a website in any particular period:
In this instance, we can replicate the SUMIF function in Excel (where the values associated with a specific identifier are summed up) by using the aggregate function in R. This can be done as follows (where raw_table is the table specified as above):
sumif_table<-aggregate(. ~ names, data=raw_table, sum)
Thus, the values associated with identifiers (in this case, names) are summed up as follows:
As per the examples at Stack Overflow, the plyr and data.table libraries can also be used to accomplish the same result as follows:
ddply(nametable, .(names), summarise, Sum_webvisits = sum(webvisits), Sum_minutesspent = sum(minutesspent))
DT <- as.data.table(nametable)
DT[ , lapply(.SD, sum), by = "names"]