# R Programming/Working with data frames

R Programming
* R Basics
** Introduction
** Sample Session
** Manage your workspace
** Settings and Installation
** Documentation
** Control Structures
** Working with functions
** Debugging
** Using C or Fortran
** Utilities
** Estimation utilities
** Packages
* Data Management
** Data types
** Working with data frames
** Importing and exporting data
** Text Processing
** Times and Dates
* Graphics
** Grammar of graphics
* Publication quality output
* Descriptive Statistics
* Mathematics
** Optimization
** Probability Distributions
** Random Number Generation
* Statistical Core Methods
** Maximum Likelihood
** Method of Moments
** Bayesian Methods
** Bootstrap
** Multiple Imputation
** Nonparametric Methods
* Regression Models
** Linear Models
** Quantile Regression
** Binomial Models
** Multinomial Models
** Tobit And Selection Models
** Count Data Models
** Duration Analysis
* Time Series
* Factor Analysis
* Classification
** Ordination
** Clustering
* Network Analysis
* High Performance Computing
** Profiling R code
** Parallel computing with R
* Appendix
** Sources
** Index
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 (.Rda or .Rdata), you can load them in memory using load. You can save data to the R format using save.

## Example Datasets

* Most packages include example datasets to test the functions.
* The data 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.
* str_data (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 gsource (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:
* str(df) gives a very brief description of the data
* names(df) gives the name of each variable
* summary(df) gives some very basic summary statistics for each variable
* head(df) shows the first few rows
* tail(df) shows the last few rows.

## Browsing data

* You can browse your data in a spreadsheet using View. 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 head and the last lines using tail.
* RStudio has a nice data browser (View(mydata)).
* 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 cbind and rbind 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 cbind command the following statement should be TRUE:
To see more samples, you can always do ?base::cbind and ?base::rbind.

## 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 mydat1$var1 and mydat2$var1). 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 attach.

## 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.
* duplicated looks at duplicated elements and returns a logical vector. You can use table to summarize this vector.
* Duplicated (sfsmisc) generalizes this command. Duplicated only marks unique values with "NA".
* remove.dup.rows (cwhmisc).
* unique keeps only the unique lines in a dataset.
* distinct (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 rename function in the reshape package.

## Creating a subset of the data

One can subset the data using subset. 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 subset 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 select option.

## Sorting and ordering

* order
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

* is.na returns a logical vector equal to TRUE if any of the variable in a dataset is missing and to FALSE otherwise.
* complete.cases 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. reshape reshapes a dataset in a wide or long format.
* varying gives the numbers of the columns which are time-varying
* v.names gives the prefix of the time-varying variables
* direction gives the direction, either "long" or "wide".
* See also :
** reShape (Hmisc)
** See Hadley Wickham's reshape package
** See Duncan Murdoch's tables package

### External links

* Printing nested tables in R – bridging between the {reshape} and {tables} packages

## 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 expand 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 rep 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.

## References

* ↑ The AER Package http://cran.r-project.org/web/packages/AER/index.html
* ↑ The EcDat Package http://cran.r-project.org/web/packages/Ecdat/index.html
* ↑ "An investigation into the causes of changes in pauperism in England, chiefly during the last two intercensal decades (Part I.)" - GU Yule - Journal of the Royal Statistical Society, June 1899, p 283
* ↑ Reshaping Data with the reshape Package : http://www.jstatsoft.org/v21/i12
* ↑ vignette for the tables package: http://cran.r-project.org/web/packages/tables/vignettes/tables.pdf
* ↑ Merging data frames while preserving the rows
* ↑ R Data Manual http://cran.r-project.org/doc/manuals/R-data.html
* ↑ Paul Murrell introduction to Data Technologies http://www.stat.auckland.ac.nz/~paul/ItDT/