Appendix G. Troubleshooting: Why Doesn’t My Code Work?

Beginners at almost anything will make mistakes. Fortunately, beginners with R receive error messages when they make mistakes, indicating what needs to be changed. Unfortunately, those messages are often cryptic and seem to be written in a language that only vaguely resembles English. A little experience with R will smooth the difficulties in a short time. The following pages include some examples of easily made errors and messages that accompany them. You should know that I have made each of the following errors myself, some of them many times!

Misspelling

One of the most common mistakes is simple misspelling. R, however, apparently does not have the word “misspelling” in its vocabulary and therefore labels this problem in sundry other ways:

> attach(trees)
> plt(Girth, Height)
Error: could not find function "plt"

In this example, R suggested that we wanted to use a function that does not exist, or is hiding, but it was a simple spelling error! Retype the command with the correct spelling:

> plot(Girth, Height)

Actually, you do not need to retype the whole command. In the preceding example it is not a big deal, but sometimes you will have a long line that it would be quite tedious to repeat. In that case, there are two shortcuts:

  • Copy and paste the incorrect line to the most recent prompt (>) and fix the error before pressing Return (or Enter).

  • Press the up-arrow key; the previous line will be copied, and you can edit it. If you press the up-arrow key twice, the command two lines above will be copied, and so on.

Here’s another example:

> plot(Girth, Height, color = "red")
Warning messages:
1: In plot.window(...) : "color" is not a graphical parameter
2: In plot.xy(xy, type, ...) : "color" is not a graphical 
   parameter
3: In axis(side = side, at = at, labels = labels, ...) :
  "color" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
  "color" is not a graphical parameter
5: In box(...) : "color" is not a graphical parameter
6: In title(...) : "color" is not a graphical parameter

This set of messages looks terrifying, but when you read each line, you can see that R simply cannot get over our using the word “color.” To find the correct abbreviation, type ?plot, and all is forgiven. Simply change color to col, as shown here, and this now works just fine:

> plot(Girth, Height, col = "red")

Take a look at this next example:

> library(poltrix)
Error in library(poltrix) : there is no package called 'poltrix'

Indeed, there is no package named poltrix. Check the spelling!

> library(plotrix)

No problem now! Notice that each of the three examples in this section were, interpreted loosely, spelling errors. Nonetheless, R gave three entirely different responses. This shows that error messages are not always to be interpreted literally. You just need to have a little experience to understand what the messages could mean.

Confusing Uppercase/Lowercase

Remember that R treats uppercase and lowercase versions of the same letter as if they were completely different letters.  In this example, R cannot find the object height because there is no such object:

> attach(trees)
> plot(Girth, height)
Error in xy.coords(x, y, xlabel, ylabel, log) : object 'height' 
not found

Change height to Height and the command will work. If you cannot remember the right variable name, you can use the str(trees) command or head(trees) to find the precise name.

Too Few (or Too Many) Parenthesis Signs

In the following example, R does not execute the command and prints + instead of >:

> plot(density(Girth)
+

This means that R was expecting something more. In this particular case, typing one more right (close) parenthesis sign, after the +, would make everything work.

In the next example, there are too many parentheses. The error message points to the culprit:

> plot(density(Girth)))
Error: unexpected ')' in "plot(density(Girth)))"
>

When using parenthetical expressions, the number of left parenthesis signs must be equal to the number of right parenthesis signs. If you have long commands, it is a good idea to count “lefts” and “rights” before you press the Return key.

Forgetting to Load a Package

Remember that any extra packages that you have installed—not in base R—must be loaded for each session in which you intend to use them. Suppose that you want to do some analysis of the Nightingale dataset from the HistData package, and you receive this message:

> attach(Nightingale)
Error in attach(Nightingale) : object 'Nightingale' not found
>

This is similar to the error message that a misspelling generates, but it’s produced for a very different reason. The solution here is to load HistData first:

> library(HistData)
> attach(Nightingale)

You can then use any commands or datasets in HistData without having to load it again until you quit R. If you want to use anything in HistData the next time you start R, you will need to load it again.

Forgetting to Install a Package

Many examples in the book load a package by  using the library() command. Remember that to load a package, you first must have installed it by using the install.packages() function, or you’ll see a message such as this:

> library(abctools)
Error in library(abctools) : 
  there is no package called 'abctools'

You only need to install a package once. It will reside on your computer forever. However, you must load it for every session in which you need it.

When I typed the command in the preceding example, I did not have the abctools package installed on my computer. I could install it by using this command:

> install.packages("abctools")

It would be even better if I used the command:

> install.packages("abctools", dependencies = TRUE)

This command not only installs abctools, it also installs any other packages that abctools might depend on; that is, packages that abctools itself uses. On Windows-based computers, you can also install packages by going to the Packages menu and selecting Install Package(s). A “CRAN mirror” window opens; either select a mirror site or use the one that is already highlighted and press OK. Then, select the package you want. Mac users can go to the Packages & Data menu, select Package Installer, click the Get List button, and then select a package.

After the first few chapters, this book does not remind you to install a package every time library() appears. I assume that you already know you need to do this, having done it several times. If you are not sure whether you have previously installed a package, you can see what packages you have by using this command:

> installed.packages()  # "installed" not "install"

This command might give you more information than you want, but it works on all R systems. A more convenient way to see what you have on Windows-based machines is to go to the Packages menu and select Load Packages. For Macintosh computers, go to the Packages & Data menu and select Package Manager.

A Dataset in a Loaded Package Is Not Found

When you load a package, the datasets included in that package should be available to use:

> library(reshape2)   # load a package
> head(tips)         # use a dataset in that package

  total_bill  tip    sex smoker day   time size
1      16.99 1.01 Female     No Sun Dinner    2
2      10.34 1.66   Male     No Sun Dinner    3
3      21.01 3.50   Male     No Sun Dinner    3
4      23.68 3.31   Male     No Sun Dinner    2
5      24.59 3.61 Female     No Sun Dinner    4
6      25.29 4.71   Male     No Sun Dinner    4

This one worked just as it should have. Sometimes, though, something goes wrong and R cannot find the data:

> library(epicalc)
Loading required package: foreign
Loading required package: survival
Loading required package: splines
Loading required package: MASS
Loading required package: nnet
Warning message:
'.find.package' is deprecated.
Use 'find.package' instead.
See help("Deprecated")

> head(Ectopic)
Error in head(Ectopic) : object 'Ectopic' not found

Ectopic is a dataset in the package epicalc, but even though the package has just been loaded, R says it cannot find the dataset. When that happens, you can add one more step, calling the data() function, to load the particular dataset that you want:

> data(Ectopic)
> head(Ectopic)
  id outc      hia gravi
1  1 Deli  ever IA   1-2
2  2 Deli  ever IA   3-4
3  3 Deli never IA   1-2
4  4 Deli never IA   1-2
5  5 Deli never IA   1-2
6  6   IA  ever IA   1-2

Now, all is right with the world!

Leaving Out a Comma

Commas show R where one argument ends and another begins. What happens if you leave one out?

> plot(Girth, Height col = "red")
Error: unexpected symbol in "plot(Girth,Height col"

The unexpected symbol was anything other than a comma. Arguments must be separated by commas:

> plot(Girth, Height, col = "red")

Copy-and-Paste Error

The command that follows was copied from a successful execution of that same command earlier in the session. The error message might leave you scratching your head:

> > head(Nightingale)
Error: unexpected '>' in ">"

The problem here is that the copy included the prompt symbol, >, so that the command line, when pasted, had two of them. The way around this problem is do one of the following:

  • Copy only the part of the line after the >.

  • After you have pasted, delete the second > before pressing the Return key.

Directory Problems—Cannot Load a Saved File

You might have trouble retrieving a file that you know you have previously saved. Even if you spell everything correctly, R might not find the file. Possible error messages are:

cannot open the connection

and/or:

no such file or directory

The most likely reason for such an error is that you are not searching the right directory—in other words, the file is not in your working directory.

First, read the section “The Working Directory”. If that does not answer all your questions, open the working directory to see if the file in question is really there. On Windows-based computers, go to the File menu and select “Display file(s).” On a Mac, go to the File menu and select Open Document.

On either platform, if the file is not in the working directory you will need to search for it and do one of the following:

  • Move it to the working directory.

  • Change the working directory to be the directory where the file is located by using the setwd() command.

  • In the load() command, give the entire path to the file. For example, if the file you wanted was cands.rda in the directory /Users/yourname/Desktop/R Things/, you would use the command:

    load("/Users/yourname/Desktop/R Things/cands.rda")  
    # note quotes!

Ensure that you spell everything correctly and include all the slashes, quotes, and so on.

Missing File Extension

This not an R problem, per se, but something that could easily cause a problem for R users. Consider the dataset created in the section “Reading from an External File”. It was entered into a spreadsheet and exported as a CSV file. On either Windows-based or Macintosh computers, depending on what options you have selected—or neglected to select—the filename may appear to be Nimrod.Tempo.

This is because your computer is set up not to show file extensions. If we believe the filename and issue an R command with that name, R indicates that no such file exists:

> Nimrod <- read.csv("Nimrod.Tempo", header = TRUE)
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'Nimrod.Tempo': No such file or directory

If we simply add the extension to the filename, there is no problem:

> Nimrod <- read.csv("Nimrod.Tempo.csv", header = TRUE)

A similar problem can arise with scripts that you try to source if you leave off the file extension, .R:

> source("NimTotals")
Error in file(filename, "r", encoding = encoding) :
  cannot open the connection
In addition: Warning message:
In file(filename, "r", encoding = encoding) :
  cannot open file 'NimTotals': No such file or directory

On the other hand:

> source("NimTotals.R")  # works fine!

Do Not Assume That All Packages Use the Same Argument Abbreviations

Although many packages are quite consistent with base R in their use of arguments and abbreviations, not all of them are, as the error message in this next example demonstrates:

> scatterplot3d(Solar.R, Ozone, Wind, col = "blue")
Error in scatterplot3d(Solar.R, Ozone, Wind, col = "blue") :
  argument 4 matches multiple formal arguments

The ++col++ argument is almost a universal standard among R packages, but consulting the help file for scatterplot3d reveals that it is not the right option for that package. Instead, you need to use the following argument:

> scatterplot3d(Solar.R, Ozone, Wind, color = "blue")

Now, this works just fine.

Outdated Packages/Package Incompatibility

Many packages depend on certain other packages being available. If a package does not load, it might be because some other required package is absent. If an error message indicates this, for instance by naming a package or command that could not be found, it might only be necessary to install the required package. Sometimes, the particular versions of installed packages can be the problem. To check this, use the following command:

> library(help = packagename)

For example, if you have trouble loading Rcmdr, type the following:

> library(help = Rcmdr)

You will see a basic information file about the package, which includes the required/suggested packages and the necessary versions. Here is a small excerpt from this file, after the naming of the authors:

Depends:           R (>= 3.0.0), grDevices, utils, splines,
                       RcmdrMisc (>= 1.0-2), car (>= 2.0-21)
Imports:           tcltk, tcltk2 (>= 1.2-6), markdown, knitr,
                        abind
Suggests:          aplpack, colorspace, effects (>= 3.0-1),
                      e1071, foreign, grid, Hmisc, lattice, 
                      leaps,lmtest, MASS, mgcv, 
                      multcomp (>= 0.991-2), nlme, nnet, 
                      relimp, rgl, rJava, RODBC, sem
                      (>= 2.1-1)

This excerpt indicates that the version of Rcmdr installed on this computer requires R version 3.0 or later. It also depends on several other packages, such as grDevices, utils, and so, having been installed. Further, some packages must be of a certain version; for example, car must be version 2.0-21 or later. If you do not have the proper matches, Rcmdr will either not load or not work properly. The easiest way to fix this problem is simply to reinstall Rcmdr, with its dependencies:

> install.packages("Rcmdr", dependencies = TRUE)

This will install/reinstall the latest version of Rcmdr and the latest versions of its dependencies. If this does not work, you might need to reinstall R.

The help file for the package also references imports, such as tcltk, which is crucial to the GUI of Rcmdr. If you do not have this package, which normally comes as part of R, you should reinstall R. Be sure that you install the binary version. If your computer is a Mac running OS X 10.9 or higher, you will also need to install XQuartz.

Finally, there are some suggested packages. Without these, parts of Rcmdr might work, but not all of it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset