Posts tagged ‘R’

December 16, 2012

Override a non-generic method in S3 OOP system

In R OOP, you can override a generic method for your custom class. For example, you can define print() and plot() methods for an class Foo. It is also easy to overrisk a non-generic method if you use S4 OOP system, through the S4 function setGeneric(). But S3 does not have a function equivalent to setGeneric().

Suppose you want to write a method sample() for class Foo. As the built-in sample() function is not generic, simply defining sample.Foo() will break the original sample(). For example, calling

sample(10,2)

will result in the following error message:

Error in UseMethod(“sample”) :
no applicable method for ‘sample’ applied to an object of class “c(‘double’, ‘numeric’)”

Here is the correct way to override a non-generic method in S3. First, you copy the non-generic method to the default method for the generic method you want to create. Then, you create the generic method and the method for class Foo.

sample.default = sample
sample <- function(obj, ...){
  UseMethod('sample')
}
sample.Foo <- function(obj, ...){
  DoSomething()
}
Advertisements
December 6, 2012

Rank 1 update to Cholesky factorization in R

Rank 1 update can be achieved in Matlab with the built-in function cholupdate(). More details about the function can be found here:

http://www.mathworks.com.au/help/matlab/ref/cholupdate.html

In R, the recommended Matrix package has added a function updown() to handle rank 1 update. However, the documentation of that function is not easy to understand, and I find the example given is misleading. That prompted me to replicate the Matlab example with the updown() function. The resulting code snippet is shown below.

library(matrixcalc)
A <- symmetric.pascal.matrix(4)
R <- chol(A)

x <- c(0, 0, 0, 1)

A + x%*%t(x)

library(Matrix)
R <- Cholesky(Matrix(A, sparse=T))
x <- Matrix(x)
R1.sparse <- updown('+', x, R)
R1 <- as(R1.sparse, 'Matrix')


x <- Matrix(c(0, 0, 0, 1/sqrt(2)))
R1.sparse <- updown('-', x, R)
R1 <- as(R1.sparse, 'Matrix')


Note that matrices have to be in the sparse representation to be used in the updown() function.

September 6, 2012

How to tell if the R session you are running is 64 bit or 32 bit?

Under Windows, here is a simple hack to find out whether you are running a 64 bit or 32 bit R.

  1. Type the command version in the prompt.
  2. If you see arch           x86_64, then it is 64 bit. Otherwise, it is 32 bit.
Tags: