R Programming/Working with data frames

In this section, we deal with methods to read, manage and clean-up a data frame.

In R, a dataframe is a list of vectors of the same length. They don't have to be of the same type. For instance, you can combine in one dataframe a logical, a character and a numerical vector.

Reading and saving data
If data are already in an R format ( or  ), you can load them in memory using. You can save data to the R format using.

Example Datasets

 * Most packages include example datasets to test the functions.
 * The  function without argument gives the list of all example datasets in all the loaded packages.
 * If you want to load them in memory, you just need to use the data function and include the name of the dataset as an argument.
 * (sfsmisc) gives the structure of all datasets in a package.


 * Some packages include lots of datasets.
 * The datasets package
 * The AER package includes replication datasets for some important textbooks in econometrics.
 * The EcDat package includes replication archive for the Journal of Applied Econometrics, the Journal of Business and Economic Statistics, etc.

Building your own data frames
You can create a dataframe using vectors.

R has a spreadsheet-style data editor. One can use it to enter the data into a spreadsheet. Read table from the clipboard :

You can also read space delimited tables in your code using  (Zelig). Here is an example with Yule 1899 data.

You can change the column names for a dataFrame.

Describing a data frame
There are various ways to inspect a data frame, such as:
 * gives a very brief description of the data
 * gives the name of each variable
 * gives some very basic summary statistics for each variable
 * shows the first few rows
 * shows the last few rows.

Browsing data

 * You can browse your data in a spreadsheet using . Depending on your operating system, this option is not always available and the result is not always the same.
 * You can print the first lines using  and the last lines using.


 * RStudio has a nice data browser.
 * RKward has also a nice data browser
 * Paul Murrell is currently developing the rdataviewer package (pdf).

Binding row or column
Most of the times when you are working with data frames, you are changing the data and one of the several changes you can do to a data frame is adding column or row and as the result increase the dimension of your data frame. There are few different ways to do it but the easiest ones are  and   which are part of the base package: Remember that the length of the newVector should match the length of the side of the data frame that you are attaching it to. For example, in the  command the following statement should be TRUE: To see more samples, you can always do  and.

Attaching data
One of the big advantages of R over Stata is that you can deal with multiple datasets at the same time. You just need to specify the name of the dataset and a "$" symbol before each variable name ( for instance  and  ). If you only work with one dataset and you don't want to write again and again the name of the dataset as a prefix for each variable, you can use.

Detecting duplicates
When you want to clean up a data set, it is very often useful to check if you don't have the same information twice in the data. R provides some functions to detect duplicates.


 * looks at duplicated elements and returns a logical vector. You can use  to summarize this vector.
 * (sfsmisc) generalizes this command.  only marks unique values with "NA".
 * (cwhmisc).
 * keeps only the unique lines in a dataset.
 * (dplyr) retains only unique/distinct rows from a dataset.

Creating and removing variables
To create a new variable

If you want to delete a variable in a dataset, you can assign NULL to that variable :

Renaming variables

 * It is possible to rename a variable by redefining the vector of names of a data frame.
 * There is also a  function in the reshape package.

Creating a subset of the data
One can subset the data using. The first argument is the name of the dataset, the second argument is a logical condition which say which lines will be included in the new dataset and the last argument is the list of variable which will be included in the new dataset.

In the following example, we generate a fake dataset and we use the  command to select the lines and columns of interest. We choose the lines such that x1 > 0 and x2 < 0 and we only keep x1 and x2 as variables.

It is also possible to reorder the columns using the  option.

Sorting and ordering


Suppose you want to randomize the order in a data set. You just need to generate a vector from a uniform distribution and to sort following that vector.

Detecting missing values

 * returns a logical vector equal to TRUE if any of the variable in a dataset is missing and to FALSE otherwise.
 * returns a logical vector indicating TRUE if all cases are complete and FALSE otherwise.

Reshaping a dataframe
This topic is important if you deal with panel data. Panel data can be stored in a wide format with one observation per unit and a variable for each time period or in a long format with one observation per unit and time period. reshapes a dataset in a wide or long format.


 * gives the numbers of the columns which are time-varying
 * gives the prefix of the time-varying variables
 * gives the direction, either "long" or "wide".


 * See also :
 * (Hmisc)
 * See Hadley Wickham's reshape package
 * See Duncan Murdoch's tables package

Expanding a dataset
Sometimes we need to duplicate some lines in a dataset. For instance, if we want to generate a fake dataset with a panel data structure. In that case, we would first generate time invariant variables and then duplicate each line by a given scalar in order to create time-varying variables.

It is possible to use the  function in the epicalc package (since this package does not exist anymore, an option to expand is given in ). This will multiply each line by a given number.

We can also use the do it yourself solution or create our own function. The idea is simple. We create a vector which igives for each line the number of times it should be replicated (dups in the following example). Then we use the  function to create a vector which repeats the line numbers according to what we want. The last step creates a new dataset which repeats lines according to the desired pattern.

Merging dataframes
Merging data can be very confusing, especially if the case of multiple merge. Here is a simple example :

We have one table describing authors : and one table describing books We want to merge tables books and authors by author's name ("surname" in the first dataset and "name" in the second one). We use the merge command. We specify the name of the first and the second datasets, then by.x and by.y specify the identifier in both datasets. all.x and all.y specify if we want to keep all the observation of the first and the second dataset. In that case we want to have all the observations from the books dataset but we just keep the observations from the author dataset which match with an observation in the books dataset.

It is also possible to merge two data.frame objects while preserving the rows’ order by one of the two merged objects.

Resources

 * R Data Manual.
 * Paul Murrell's Introduction to Data Technologies.