Skip an error in a loop && debug in R

When writing R code, it is important to know how to debug.

    1. In for loop, once bug occurred, to to skip the error and continue loop:

count <- 0
repeat {
if (count == 100) break
count <- count + 1
x <- matrix(sample(0:2, 4, replace = T), 2, 2)
x.inv <- try(solve(x), silent=TRUE)
if ('try-error' %in% class(x.inv)) next
else inverses[[count]] <- x.inv
}

2. To test an R function, simply use debug()

when run debug() command

  • n(next): to run the next command line,and pause after next line, which gives us a way to run code line by line.
  • c(continue): to run several lines. If present in a loop, this command will run the entire loop; while in stays in a function but loop, then R will run over the function.
  • where: output present location, show the array of functions till present code line.
  • Q: exit browser.

3. Set break point setBreakpoint()

require(utils)

setBreakpoint(filename,linenumber)

  This will set break point at line number linenumber in filename. Notice this should set in a function.  This command can be used while debug() which runs the code till break point.

cancel break point :  untrace(fun)

 

Load Packages Automatically in RStudio

Recently I was doing R package development, I used 3 packages.  But the problem is that I have to run library() command every time I load the project, which annoyed me a lot. Then I found out that I can set the default packages loaded when R start up.

1. First Let’s check what default packages are:

> (.packages())
(Note that the parenthesis can not be omitted.)

2. Files in three folders are important in this process:

i>. R_HOME, the directory in which R is installed. The etc sub-directory can contain start-up files read early on in the start-up process. Find out where your R_HOME is with the R.home() command.

ii>. HOME, the user’s home directory. Typically this is /home/username on Unix machines or C:\Users\username on Windows (since Windows 7). Ask R where your home directory with, path.expand("~") (note the use of the Unix-like tilde to represent the home directory).

iii>. R’s current working directory. This is reported by getwd().

3. Then we need to locate the .Rprofile file, which is the R project default start up file.

file.path(Sys.getenv("HOME"), ".Rprofile") can help us locate the file directory.

For more information please refer to r-startup.

4. Rewrite this startup file.

> file.edit("~/.Rprofile")
# This opens up a script, within which you can enter in your library commands
library(ggplot2)
library(Rcpp)
library(plyr)
library(reshape2)

Finally you can run library() again to check whether these packages are loaded.

Thank you for your reading, This site is actively updated. Keep an eye on it if interested.