Tải bản đầy đủ
Appendix G. Troubleshooting: Why Doesn’t My Code Work?

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

Tải bản đầy đủ

Actually, you do not need to retype the whole command. In the pre‐
ceding 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 com‐
mand 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 for‐
given. 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 sec‐
tion 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.

288

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

Confusing Uppercase/Lowercase
Remember that R treats uppercase and lowercase versions of the
same letter as if they were completely different letters. In this exam‐
ple, 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 can‐
not 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 mes‐
sage points to the culprit:
> plot(density(Girth)))
Error: unexpected ')' in "plot(density(Girth)))"
>

When using parenthetical expressions, the number of left parenthe‐
sis 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 Nightin
gale dataset from the HistData package, and you receive this mes‐
sage:

Troubleshooting: Why Doesn’t My Code Work?

|

289

> 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 com‐
puter 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 abc
tools itself uses. On Windows-based computers, you can also install
packages by going to the Packages menu and selecting Install Pack‐
age(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

290

|

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

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)
> head(tips)

1
2
3
4
5
6

total_bill
16.99
10.34
21.01
23.68
24.59
25.29

# load a package
# use a dataset in that package

tip
sex smoker day
time size
1.01 Female
No Sun Dinner
2
1.66
Male
No Sun Dinner
3
3.50
Male
No Sun Dinner
3
3.31
Male
No Sun Dinner
2
3.61 Female
No Sun Dinner
4
4.71
Male
No Sun Dinner
4

This one worked just as it should have. Sometimes, though, some‐
thing 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

Troubleshooting: Why Doesn’t My Code Work?

|

291

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. Argu‐
ments 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.

292

|

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

Directory Problems—Cannot Load a Saved
File
You might have trouble retrieving a file that you know you have pre‐
viously 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 search‐
ing the right directory—in other words, the file is not in your work‐
ing directory.
First, read the section “The Working Directory” on page 10. 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 comput‐
ers, 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 com‐
mand:
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” on page 16. It was entered into a
Troubleshooting: Why Doesn’t My Code Work?

|

293

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")

294

|

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

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 ver‐
sions. Here is a small excerpt from this file, after the naming of the
authors:
Depends:
Imports:
Suggests:

R (>= 3.0.0), grDevices, utils, splines,
RcmdrMisc (>= 1.0-2), car (>= 2.0-21)
tcltk, tcltk2 (>= 1.2-6), markdown, knitr,
abind
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.
Troubleshooting: Why Doesn’t My Code Work?

|

295

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 pack‐
age, 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.

296

|

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

APPENDIX H

R Functions Introduced in This
Book

Here is a list of functions used in this book, for quick reference. It is
far from a complete list of R functions. For further information
about a given function, x, see the index, or type help(x) or ?x.

Data Input/Output
load()
Reload an R dataset previously created by using save().
open.ncdf()
Open an .ncdf file (ncdf package).
Quandl()
Read a Quandl dataset (Quandl package).
read.csv()
Read a file in .csv format and create a data frame.
read.fwf()
Read a fixed-width file.
read.spss()
Read an SPSS dataset (foreign package).
read.table()
Read a file in table format and create a data frame.

297

read.txt()
Read a file in .txt format and create a data frame.
read.xport()
Read an SAS XPORT file (foreign package).
readWorksheetFromFile()
Read an Excel spreadsheet (XLConnect package).
save()
Write an R object to the working directory or a specified file.
xmlToDataFrame()
Read an XML file (XML package).

Datasets
attach()
Select a particular dataset for the following analysis.
data()
Determine what datasets are available (with no argument) or load a
dataset.
data.frame()
Combine two or more vectors to make a new data frame.
detach()
Deselect a dataset; that is, following commands no longer analyze
that dataset.
edit()
Edit a dataset.
fix()
Edit a dataset.
head()
View selected lines of a dataset, from the top.
str()
Determine the structure of an object.
subset()
Create a subset of a specified data frame.

298

|

Appendix H: R Functions Introduced in This Book