Saturday, November 08, 2008

<R>andom Notes

1. how to estimate the running time of a R function?

R has a function proc.time() http://rweb.stat.umn.edu/R/library/base/html/proc.time.html
sample code
## a way to time an R expression: system.time is preferred
> ptm <- proc.time()
> for (i in 1:50) mad(stats::runif(500))
> proc.time() - ptm
user system elapsed 
0.039 0.001 0.052 
## End(Not run)

2. string manipulation in R

define a string
> s = "some characters"

convert other type into a string
> s = as.character(some_variable_in_other_type)

Convert a string into numbers
> pi = as.numeric("3.14159")


string length
>nchar(s)

string concatenation
> s1 = "string1"
> s2 = "string2"
> paste(s1, s2, sep = "")

given a vector of strings, vs, return a string that is the concatenation of vs's elements
> vs = c("song", "qiang")
> paste(vs, collapse = "")
 "song qiang"

string splicing
suppose s is a string, how do we slice a substring of the s given starting position and ending position?
we use the following function. there is no default value for stop. it the value of stop is larger the the total
length of string, it is truncated to the length of the string
> substr(s, first = 1, stop = 12)

string split

> strsplit("song qiang", split=" ")
[1] "song" "qiang"


3. when making figures with legend box, the text expand out of legend box when we use dev.copy2eps()  to convert  the figure image to a eps file

This problem comes from the different specification of font sizes in difference devices. A ugly way to solve this problem is to specify text.width=strwidth("some string"),
where "some string"  refers to the longest legend text plus some extra characters. The optimal number of extra characters should be determined by trial and error.

4. How to handle exceptions in R?
Read about two functions try and tryCatch (R FAQ 7.32). An example with try is shown below:
for(i in 1:16)
{
   result <- try(nonlinear_modeling(i));
   if(class(result) == "try-error") next;
}

No comments: