Entering Data Within R

If you are entering a small number of observations, entering the data directly into R might be a good approach. There are a couple of different ways to enter data into R.

Many of the examples in Parts I and II show how to create new objects directly on the R console. If you are entering a small amount of data, this might be a good approach.

As we have seen before, to create a vector, use the c function:

> salary <- c(18700000, 14626720, 14137500, 13980000, 12916666)
> position <- c("QB", "QB", "DE", "QB", "QB")
> team <- c("Colts", "Patriots", "Panthers", "Bengals", "Giants")
> name.last <- c("Manning", "Brady", "Pepper", "Palmer", "Manning")
> name.first <- c("Peyton", "Tom", "Julius", "Carson", "Eli")

It’s often convenient to put these vectors together into a data frame. To create a data frame, use the data.frame function to combine the vectors:

> top.5.salaries <- data.frame(name.last, name.first, team, position, salary)
> top.5.salaries
  name.last name.first     team position   salary
1   Manning     Peyton    Colts       QB 18700000
2     Brady        Tom Patriots       QB 14626720
3    Pepper     Julius Panthers       DE 14137500
4    Palmer     Carson  Bengals       QB 13980000
5   Manning        Eli   Giants       QB 12916666

Entering data using individual statements can be awkward for more than a handful of observations. (That’s why my example above included only five observations.) Luckily, R provides a nice GUI for editing tabular data: the data editor.

To edit an object with the data editor, use the edit function. The edit function will open the data editor and return the edited object. For example, to edit the top.5.salaries data frame, you would use the following command:

> top.5.salaries <- edit(top.5.salaries)

Notice that you need to assign the output of the edit function to a symbol; otherwise, the edits will be lost. The data editor is designed to edit tabular data objects, specifically data frames and matrices. The edit function can be used with other types of objects, such as vectors, functions, and lists, but it will open a text editor.

Alternatively, you can use the fix function. The fix function calls edit on its argument and then assigns the result to the same symbol in the calling environment. For the example above, here is how you would use fix:

> fix(top.5.salaries)

On Microsoft Windows, there is a menu item “Data Editor...” under the Edit menu that allows you to enter the name of an object into a dialog box and then calls fix on the object.