[R] How to avoid switching on input type?

Gabor Grothendieck ggrothendieck at gmail.com
Sat Mar 21 19:01:07 CET 2009


Create an S3 generic lag.zerofill and then define methods for each class:

lag.zerofill <- function(x, k = 1, ...) UseMethod("lag.zerofill")
lag.zerofill.zoo <- function(x, k, ...) {
		m <- merge(x, lag(x, k), fill = 0)
		structure(m[, -(1:ncol(x))], dimnames = list(NULL, colnames(x)))
}
# lag.zerofill.list <- ...

# test
lag.zerofill(inp.zoo, -1)

Running the above gives (last line shown only):

> lag.zerofill(inp.zoo, -1)
           inp inp2
2003-02-01   0    0
2003-02-02   5    6
2003-02-03   9    6
2003-02-04   4    0
2003-02-05   2    4


On Sat, Mar 21, 2009 at 11:47 AM, Ken-JP <kfmfe04 at gmail.com> wrote:
>
> Hi,
>
> I need some help improving this ugly code I wrote.  I would like to shift
> forward a zoo object, matrix, ts, or list by "shift" items (default 1) and
> fill the holes with 0's.
>
> The code below works, but it looks ugly.  I could write a function
> lag.zerofill() which calls the two functions below depending on the class()
> of the item passed in, but that feels very unlike R.
>
> What is the proper way to write this code so that it works for all input
> types?
>
> Is a switch depending on the input type really necessary?  I am hoping the
> answer is "no".
>
> Thanks in advance.
>
> - Ken
>
> #
> -----------------------------------------------------------------------------------
>
> require( zoo );
>
> inp <- c( 5, 9, 4, 2, 1 ); inp2 <- c( 6, 6, 0, 4, 2 );
> inp.zoo <- zoo( cbind( inp, inp2 ), as.Date("2003-02-01") +
> (0:(length(inp)-1)));
>
> lag.zerofill.list <- function( m, shift=1, ...) {
>  c( rep(0,shift), m[-((length(m)-shift+1):length(m))] );
> }
>
> lag.zerofill.zoo <- function( m, shift=1, ...) {
>  k <- rbind( m[1:shift,], lag(m,-(shift))); k[1:shift,] <- 0; k;
> }
>
> lag.zerofill.list( inp ) # works ok
> lag.zerofill.zoo( inp.zoo ) # works ok
>
> --
> View this message in context: http://www.nabble.com/How-to-avoid-switching-on-input-type--tp22637249p22637249.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list